【发布时间】:2014-10-24 21:52:40
【问题描述】:
到目前为止,我发现使用 Fluent API 更改数据库模型的所有可能性都假设我要编辑的属性也作为实体中的属性存在。但是我不知道如何更改属性的属性,这不是实体类中的属性。
例子:
public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Address> Addresses { get; set; }
public Person()
{
this.Addresses = new List<Address>();
}
}
public class Address
{
public int AddressId { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
现在 Code First 创建一个数据库,其中 Addresses 表将 PersonId 作为 FK,因此具有 1-to-* 关系(我想要什么)。但是 Addresses 中的 FK PersonId 可以为空,并且我无法在 Fluent API 中访问此 FK,因为没有属性。如何将此 FK 更改为不可为空?
另外,当我想删除一个人时,EF 不允许我这样做,因为有一个关联的地址。我认为行为是:
- nullable FK:删除有问题的记录,将子记录FK设置为null
- 不可为空:错误,或删除记录以及所有关联记录(取决于级联规则)
这不正确吗?
【问题讨论】:
标签: c# sql .net entity-framework foreign-key-relationship