实体框架代码在组合键上的第一个一对一关系 [英] Entity Framework Code First One to One relationship on composite key

查看:60
本文介绍了实体框架代码在组合键上的第一个一对一关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我要实现的是我有三个表,一个父级将始终在其中有一个条目,而其他两个表中的只有一个将被填充.我要处理的复杂性是表的主键是两个字段的组合

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]

我想知道是否有人建议最好通过Fluent API通过EF Code First做到最好.

I was wondering if anyone has any suggestions on how best to do this through EF Code First preferably using the 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.

这篇关于实体框架代码在组合键上的第一个一对一关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆