entity framework 5 - One to Zero or One relationship with EF5 fluent mapping -
i have 3 entities:
public class mainentity() { public long id { get; set; } public long entityaid { get; set; } public entitya optionalentitya { get; set; } public long entitybid { get; set; } public entityb optionalentityb { get; set; } public string sprop { get; set; } } public class entitya() { public long id { get; set; } public long mainentityid { get; set; } public mainentity requiredentity { get; set; } } public class entityb() { public long id { get; set; } public long mainentityid { get; set; } public mainentity requiredentity { get; set; } }
all 3 entities have there own id generated database:
property(t => t.id).hasdatabasegeneratedoption(databasegeneratedoption.identity);
how can define relationship between mainentity , entitya , entityb in order have:
- mainentity may have 0 or 1 entitya
- mainentity may have 0 or 1 entityb
- entitya must have 1 mainentity
- entityb must have 1 mainentity
in mainentityconfigurationmap have defined relation this:
hasoptional(m => m.optionalentitya).withrequired(ea => ea.requiredentity); hasoptional(m => m.optionalentityb).withrequired(eb => eb.requiredentity);
looking @ generated migration have entitya:
createtable( "dbo.entitya", c => new { id = c.long(nullable: false, identity: true), mainentityid = c.long(nullable: false), }) .primarykey(t => t.id) .foreignkey("dbo.mainentity", t => t.id) .index(t => t.id);
entity framework defining shared primary key here, there way avoid , make mainentityid poiting mainentity.id?
entity framework supports one-to-one relation on top of shared primary key (pk in dependent table fk principal table). reason fk in dependent table must unique enforce one-to-one relation ef doesn't support unique constraint (except pk).
Comments
Post a Comment