我不认为我想做的事情是疯狂的。我有一个具有一个地址的 Person 实体。我不想将 PersonId
作为我的 Address 实体中的属性。当我尝试保存到数据库时,EF Core 不断提示我无法将 NULL 插入到地址表的 PersonId
列中。
public class Person
{
public int Id { get; private set;}
public string Name { get; private set;}
public Address Address { get; private set;}
// .. constructor etc
}
public class Address
{
public int Id { get; private set;}
public string Street { get; private set;}
// .. constructor etc
}
数据库表:
人员:ID、姓名
地址:ID、街道、PersonId
或者我是否需要在两侧都有引用导航属性,这看起来真的很愚蠢。
最佳答案
如果您有 1:1 的人员:地址,您也可以使用值对象。太棒了。
在 EF 的 DbContext 中注册的主要对象
public DbSet<Person> Persons { get; set; }
public class Person
{
public int Id { get; private set;}
public string Name { get; private set;}
public Address address { get; private set;}
// .. constructor etc
}
您的地址对象作为具有属性[Owned]
的值对象
[Owned]
public class Address
{
public int Id { get; private set;}
public string Street { get; private set;}
}
然后在DbContext中设置映射OnModelCreating
modelBuilder.Entity<Person>().OwnsOne(o => o.Address);
EF 会将您的值对象生成到 Person 表中,但在您的应用程序中您将有两个对象。
关于c# - EF Core 2.0 一对一 - 这是什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53678901/