Entity Framework Code-First Load Multiple Children From Single Table -
i using entityframework 5.0 code-first. have poco class foo this:
public class bar { public int fooid { get; set; } public virtual foo foo { get; set; } public int otherfooid { get; set; } public virtual foo otherfoo { get; set; } } in dbcontext, lazy loading turned on. when load foo context, property "foo" lazy loaded expected using fooid foreign key. "otherfoo" not loaded, no matter how try.
foo f = bar.foo; // proxy type, loads in data db correctly foo f = bar.otherfoo; // null, not lazily loaded foo f = context.bars.include("otherfoo").first(...).otherfoo; // still null (in case matters, have userprofile table, , model objects have createdbyuser , lastmodifiedbyuser fields, neither of work unless rename 1 , associated *id field "user")
is there attribute can stick on these fields tell entity how load them, or there can set in dbcontext.onmodelbuilding method if override it?
i guess mapping problem ef not recognize otherfooid foreign key otherfoo. otherfooid not nullable , relationship required, i.e. there must related otherfoo in database (unless have fk constraint enforcement turned off in db).
you can specify foreign key explicitly data annotations ...
[foreignkey("otherfoo")] public int otherfooid { get; set; } ... or fluent api:
modelbuilder.entity<bar>() .hasrequired(b => b.otherfoo) .withmany() // add f => f.otherbars here, if have collection in foo .hasforeignkey(b => b.otherfooid); if exception "multiple cascading delete paths not allowed" append
.willcascadeondelete(false); at end of fluent mapping.
Comments
Post a Comment