简体   繁体   English

实体框架代码复合密钥的第一对一关系

[英]Entity Framework Code First One to One relationship on composite key

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. 我想知道是否有人建议如何通过EF Code First最好地使用Fluent API。

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. 您必须在应用程序的业务逻辑中处理此限制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架代码优先于隐含组合键的可选一对多关系 - Entity Framework Code First Optional One to Many Relationship on implied Composite Key 实体框架代码优先的一对一关系 - One to One relationship in Entity Framework Code First 实体框架-代码优先-共享主键一对多关系 - Entity Framework - Code first - One to Many relationship with shared primary key 实体框架6首先将多个表与一个外键关系代码 - Entity Framework 6 multiple table to one foreign key relationship code first 一键至二键和一键至第三键Entity Framework 6代码优先 - Composite key one to second and one to third Entity Framework 6 code-first Entity Framework 5.0代码首先是一对一和一对多的关系 - Entity Framework 5.0 code first one to one and one to many relationship 一对一关系,不同的键列名称,实体框架,代码优先方法 - One to one relationship, different key column name, Entity Framework, Code First approach Entity Framework 5.0代码优先方法中的一对一关系 - One to one relationship in Entity Framework 5.0 Code First Approach 实体框架代码优先方法-一对一关系 - Entity framework code first approach - one to one relationship 如何在实体框架中(代码优先)配置一对一关系 - How to configure One-to-One Relationship in Entity Framework, Code First
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM