c# - Entity Framework Populating Child Objects using Foreign Key -


i hope isn't duplicate have been looking looking more @ reasoning behind this.

i have set user object.

public class user {     public user()     {      }      [key]     [databasegenerated(databasegeneratedoption.identity)]     public int userid { get; set; }     public guid userguid { get; set; }     public string email { get; set; }     public string name { get; set; }     public int companyid { get; set; }     public int statusid { get; set; }     [foreignkey("statusid")]     public status status { get; set; }     public int roleid { get; set; }     [foreignkey("roleid")]     public userrole userrole { get; set; } } 

and child objects

public class userrole {     [key]     [databasegenerated(databasegeneratedoption.identity)]     public int roleid { get; set; }     public string role { get; set; } }  public class status {     [key]     public int statusid { get; set; }     public string description { get; set; } } 

when call

var testuser = dbcontext.user.where(u => u.companyid == 1).firstordefault(); 

i users.status being null, users.statusid = 1.

however, if call

var status = dbcontext.status.tolist(); var role = dbcontext.userrole.tolist(); var testuser = dbcontext.user.where(u => u.companyid == 1).firstordefault(); 

then call testuser.status, can see correct object related statusid of 1.

can explain why solve issue , how can make work without having call following beforehand.

var status = dbcontext.status.tolist(); 

thanks

just use property this. keyword virtual put property lazy loading , can access whole object.

public virtual status status { get; set; } 

and btw, edited class. there un-needed things, because can access statusid property status (like int statid = status.statusid;) , same userrole.

public class user {     public user()    {     }     [key]    [databasegenerated(databasegeneratedoption.identity)]    public int userid { get; set; }    public guid userguid { get; set; }    public string email { get; set; }    public string name { get; set; }    public int companyid { get; set; }    public virtual status status { get; set; }    public virtual userrole userrole { get; set; }    } } 

Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -