具有单独ID属性的EF6一对一关系 [英] EF6 One-To-One relationship with separate ID property
问题描述
我们需要定义以下实体之间的一对一关系:
We need to define a One-To-One relationship between following entities:
public class Foo
{
[Key, Column("Foo_ID")]
public int Id { get; set; }
public Bar Bar { get; set; }
}
public class Bar
{
[Key, Column("Bar_ID")]
public int Id { get; set; }
[Column("Bar_Foo_ID")]
public int? FooId { get; set; }
public Foo Foo { get; set; }
}
我们需要迁移旧版软件,并使它们同时运行现在。因此,我们无法更改任何关系。不幸的是,数据库中没有定义任何外键。
We need to migrate a legacy software and have both of them running side by side for now. So we can't change any relations. Unfortunately there are no foreign keys defined in the database.
modelBuilder.Entity<Foo>()
.HasOptional(a => a.Bar)
.WithRequired(x => x.Foo)
.WillCascadeOnDelete(true);
当我们查询 Foo
和 Include(x => x.Bar)
它使用 LEFT OUTER JOIN条在Foo_ID = Bar_ID
上创建一个SQL查询,这是错误的。
When we query Foo
and Include(x => x.Bar)
it creates a SQL query with LEFT OUTER JOIN bars ON Foo_ID = Bar_ID
which is wrong.
我们需要将其更改为Foo_ID = Bar_Foo_ID 上的 LEFT OUTER JOIN条形,但我不是确保Entity Framework如何支持它,因为我们在数据库中没有外键,而
Bar_ID
作为PrimaryKey。
We need to change this to a LEFT OUTER JOIN bars on Foo_ID = Bar_Foo_ID
, but I'm not sure how Entity Framework supports that as we don't have foreign keys in our DB and Bar_ID
as PrimaryKey.
我知道一个 Foo
可能有多个 Bars
,但是有一种方法可以强制执行一个一对一关系?
I know that there can be potentially more than one Bars
for one Foo
, but is there a way to enforce a One-To-One relationship?
创建 Foo
时,会出现一个 Bar 总是为此创建code>。
推荐答案
对于旧数据,可以使用以下命令:
For legacy data, you can use the following:
1:0-1关系基本上是1:许多关系的一种特殊形式。
1 : 0-1 relationships are basically a special form of 1 : many relationships.
因此您可以将关系配置为1:实体框架中有很多,并可能添加唯一索引到外键属性以强制执行最大约束。
So you can configure the relation as 1:many in entity framework and potentially add a unique index to the foreign key property to enforce your constraint of max. one related entry.
public class Foo
{
[Key, Column("Foo_ID")]
public int Id { get; set; }
// this can't be a single reference property unfortunately... but it will only contain 0 or 1 object when working with it.
public ICollection<Bar> Bars { get; set; }
}
public class Bar
{
[Key, Column("Bar_ID")]
public int Id { get; set; }
[Index(IsUnique = true)]
[Column("Bar_Foo_ID")]
public int? FooId { get; set; }
public Foo Foo { get; set; }
}
modelBuilder.Entity<Foo>()
.HasMany(a => a.Bars)
.WithRequired(x => x.Foo)
.HasForeignKey(x => x.FooId)
.WillCascadeOnDelete(true);
这篇关于具有单独ID属性的EF6一对一关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!