entity framework - EF7 Read Master Detail Records -
i'm trying head around ef7 writing simple master-detail relationship sqlite database. saving works fine, reading gives me headaches:
here entities:
public class message { public int messageid { get; set; } public string name { get; set; } public list<messagepart> messageparts { get; set; } } public class messagepart { public int messagepartid { get; set; } public string text { get; set; } public int messageid { get; set; } public message message { get; set; } }
createmessage() supposed to:
static void createmessages() { using (var db = new testcontext()) { var m1 = new message { name = "train_arrives_in_x_minutes", messageparts = new list<messagepart>() { new messagepart { text = "train arrives in 5 minutes" }, new messagepart { text = "zug faehrt in 5 minuten ein", } } }; var m2 = new message { name = "train_out_of_service", messageparts = new list<messagepart>() { new messagepart { text = "train out of service" }, new messagepart { text = "kein service auf dieser strecke", } } }; db.messages.add(m1); db.messages.add(m2); var count = db.savechanges(); console.writeline("{0} records saved database", count); } }
reading existing database reads master record fine, detail recordset pointer stays null.
static void readmessages() { using (var db = new testcontext()) { foreach (message m in db.messages) { console.writeline(m.name); // exception here: m.messageparts null foreach(messagepart mp in m.messageparts) { console.writeline("mp.text={0}", mp.text); } } } }
is there can force messagesparts load? i've worked other (python) orms before , never had problem before. problem lazy loading? tried fetch childrecords using linq statement, didn't either. looks in database though.
if want enable lazyloading need enable lazyloading (should enabled default) , make property virtual:
public testcontext() : base(name = "conntextionname") { this.configuration.proxycreationenabled = true; this.configuration.lazyloadingenabled = true; }
and models shuodl like:
public class message { public int messageid { get; set; } public string name { get; set; } public virtual icollection<messagepart> messageparts { get; set; } } public class messagepart { public int messagepartid { get; set; } public string text { get; set; } public int messageid { get; set; } public virtual message message { get; set; } }
if not want use lazyloading, can load related entities using eager loading:
using system.data.entity; using (var db = new testcontext()) { int messageid = ....; message message = db.messages .where(m => m.messageid == messageid) .include(m => m.messageparts) // eagerly load message parts .firstordefault(); // message , related message parts loaded , ready. }
for more information, please have @ this site.
Comments
Post a Comment