c# - Accessing parent values via foreign keys -
models:
public class school { public int id {get;set;} public string schoolname {get;set;} public virtual icollection<room> rooms {get;set;} } public class room { public int id {get;set;} public string roomname {get;set;} public int schoolid {get;set;} [foreignkey("schoolid")] public virtual school school {get;set;} public virtual icollection<computer> computers {get;set;} } public class computer { public int id {get;set;} public string computername {get;set;} public int roomid {get;set;} [foreignkey("roomid")] public virtual room room {get;set;} }
so, have computer object , trying access school name, like:
computer mycomp = context.computers.firstordefault(); string schoolname = mycomp.school.schoolname;
and getting null object in return. can point me in right direction why doesn't work?
when querying object need tell entity framework want include related object. here how can using include:
computer mycomp = context.computers.include(c => c.school).firstordefault();
make sure include namespace method lives:
using system.data.entity;
c# asp.net-mvc entity-framework code-first dbcontext
No comments:
Post a Comment