c# - Entity Framework Doesn't create a new proxy Why? -
i've got trouble ef (6.0.0)
here code
var answer = new ticketanswer(); answer.answer = "hello"; answer.ticketid = 20; answer.confirmdate = datetime.now; db.ticketanswer.add(answer); db.savechanges(); answerid = answer.id; db.ticketanswer.where(x=> x.id == answerid).firstordefault();
after , when im trying db.ticketanswer same id of answer (which new created) ef returning ticketanswer class (not proxy) , cant access ticket class on (ticket property null ticketid not null , there ticket on db id = 20 , there not problem relations) , when change query :
var = db.ticketanswer.where(x => x.id == 225).firstordefault();
ef returning system.data.entity.dynamicproxies_asdgafd... , can access ticket class.
all want , reach ticket class on ticketanswer class , should ?
your navigation property has not yet loaded newly added entity in context. load must:
var ticketanswer = db.ticketanswer.include(ta => ta.ticket).where(x=> x.id == answerid).firstordefault();
or better:
var ticketanswer = db.ticketanswer.include(ta => ta.ticket).single(ta=> ta.id == answerid);
one may ask "then why other entity (with id == 225) loaded without using .inlcude thing?"
the answer is: entity added surely , other run session, using other db context instance. entity in not in cache of current db context instance. when asking it, ef load it, , navigation properties available without explicit include. freshly added entity in cache, no navigation properties. simple asking using give same instance you've added. note: not same entity: same instance.
to navigate multiple hops in entity graph can use:
.include("ticket.user") // in case if ticket entity has navigation property called 'user'
Comments
Post a Comment