Entity Framework 必填 属性 无关系
Entity Framework Required Property Without Relationship
给定
class Foo()
{
Guid FooId;
Bar Bar;
}
class Bar()
{
Guid BarId;
}
Bar
是 Foo
的必需 属性,但 Foo
和 Bar
之间没有数据库关系。将 Foo
分配给 Bar
后,可以从数据库中删除 Bar
而无需删除任何 Foo
.
这个在fluent中是怎么配置的API?如果我尝试
entity.Property(e => e.Bar)
.IsRequired();
Entity Framework 迁移抛出错误
The property 'Bar' cannot be added to the entity type 'Foo' because a navigation property with the same name already exists on entity type 'Foo'
如果我尝试 entity.HasOne(e => e.Bar).WithMany().IsRequired();
Entity Framework 在数据库中创建 Foo
和 Bar
之间的关系。
如何在不建立关系的情况下使 Bar
成为 Foo
的必需 属性?
选项一
class Foo()
{
Guid FooId;
Guid BarId;
}
没有对象引用 - 没有关系。默认需要guid,不需要额外配置。您可以在此处输入任何值,即使不存在具有此 BarId 的 Bar
条记录。
选项二
你的另一种方法是 create/have 关系,强制参照完整性,但有级联选项 SetNull
:
fooEntity.HasOne(x => x.Bar).WithMany().OnDelete(DeleteBehavior.SetNull);
这个(你应该检查你的数据库 provider/engine 是否支持这个)在你删除 Bar
它链接到的时候不会删除 Foo
。相反,Foo.BarId
将被设置为 null
。当然,这会导致 Foo
table 中的 BarId
字段具有可为空的列类型。
给定
class Foo()
{
Guid FooId;
Bar Bar;
}
class Bar()
{
Guid BarId;
}
Bar
是 Foo
的必需 属性,但 Foo
和 Bar
之间没有数据库关系。将 Foo
分配给 Bar
后,可以从数据库中删除 Bar
而无需删除任何 Foo
.
这个在fluent中是怎么配置的API?如果我尝试
entity.Property(e => e.Bar)
.IsRequired();
Entity Framework 迁移抛出错误
The property 'Bar' cannot be added to the entity type 'Foo' because a navigation property with the same name already exists on entity type 'Foo'
如果我尝试 entity.HasOne(e => e.Bar).WithMany().IsRequired();
Entity Framework 在数据库中创建 Foo
和 Bar
之间的关系。
如何在不建立关系的情况下使 Bar
成为 Foo
的必需 属性?
选项一
class Foo()
{
Guid FooId;
Guid BarId;
}
没有对象引用 - 没有关系。默认需要guid,不需要额外配置。您可以在此处输入任何值,即使不存在具有此 BarId 的 Bar
条记录。
选项二
你的另一种方法是 create/have 关系,强制参照完整性,但有级联选项 SetNull
:
fooEntity.HasOne(x => x.Bar).WithMany().OnDelete(DeleteBehavior.SetNull);
这个(你应该检查你的数据库 provider/engine 是否支持这个)在你删除 Bar
它链接到的时候不会删除 Foo
。相反,Foo.BarId
将被设置为 null
。当然,这会导致 Foo
table 中的 BarId
字段具有可为空的列类型。