Entity Framework Code First One to One relationship on composite key

删除回忆录丶 提交于 2019-12-21 19:59:15

问题


Basically what I am trying to achieve is I have three tables, one parent will always have an entry in it and only one of the other two tables will be populated. The complexity that I am dealing with is that the primary key for the tables is the combination of two fields

ParentTable
-----------
UniqueID
OwnerID
[Some more fields]


ChildTable1
-----------
UniqueID
OwnerID
[Some more fields]


ChildTable2
-----------
UniqueID
OwnerID
[Some more fields]

I was wondering if anyone has any suggestions on how best to do this through EF Code First preferably using the Fluent API.


回答1:


You just need to define that the primary keys are composite...

modelBuilder.Entity<Parent>().HasKey(p => new { p.UniqueID, p.OwnerID });
modelBuilder.Entity<Child1>().HasKey(c => new { c.UniqueID, c.OwnerID });
modelBuilder.Entity<Child2>().HasKey(c => new { c.UniqueID, c.OwnerID });

...and then define the two one-to-one relationships:

modelBuilder.Entity<Parent>()
    .HasOptional(p => p.Child1)
    .WithRequired(); // or .WithRequired(c => c.Parent)

modelBuilder.Entity<Parent>()
    .HasOptional(p => p.Child2)
    .WithRequired(); // or .WithRequired(c => c.Parent)

You cannot define a constraint though (except probably by defining a trigger in the database) that would ensure that a given parent may only refer to one of the two children, but not to both. You must handle this restriction in your application's business logic.



来源:https://stackoverflow.com/questions/13249438/entity-framework-code-first-one-to-one-relationship-on-composite-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!