c# - Entity Framework proxycreation misery -


ive seen quite few solutions on problems similar mine. none of them satisfied needs specifically.

i have following setup:

public class user {     public int32 id { get; set; }     public string name { get; set; }     public virtual list<phonebook> phonebooks { get; set; } }  public class phonebook {     public int32 id { get; set; }     public virtual int32 userid { get; set; }     public virtual user user { get; set; }     public string title { get; set; }     public virtual list<phonenumber> number { get; set; } }  public class phonenumber {     public int32 id { get; set; }     public string num { get; set; }     public virtual int32 phonebookid { get; set; }     public virtual phonebook phonebook { get; set; } } 

now can query fine. problem circular referencing.

let's want select every phonebook thats user id = 1 query context.phonebook.where(x=>x.userid == 1) load user , every phonenumber well. turn off proxying , nothing phonebook ( no numbers, no user ).

what if wanted every phonenumber not user? i'd have make sure getting phonenumber objects doesnt mean it's getting phonebook related number too. kind of need proxying go 1 way. down ladder , not upwards.

first of all, foreign key ids not need virtual. use virtual navigation properties (or other entity type properties) only: foreign key not navigation property, it's integer.

now question not related proxies really, it's related lazy loading (proxies enable lazy loading default, why concerned them, that's not necessary).

if want load specified entities, disable lazy loading , eager loading:

context.configuration.lazyloadingenabled = false;  // load phonebook entries , users matching id var result = content.phonebook                 .include(x => x.number)                 .include(x => x.user)                 .where(x => x.userid == 1);   // load phonebook entries without users     var result2 = content.phonebook                 .include(x => x.number)                 .where(x => x.userid == 1);  

that simple

ps: proxies have more advantages them lazy loading (like change tracking, etc.). if problem lazy loading, turn lazy loading off, not proxies.


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

css - Can I use the :after pseudo-element on an input field? -