实体框架一对一关系
本文关键字:关系 一对一 框架 实体 | 更新日期: 2023-09-27 18:37:13
我首先在
应用程序中使用实体框架 6 代码使用以下模型。
public class Customer
{
public Customer
{
}
public int Id { get; set; }
public string Name { get; set; }
public virtual Address Address { get; set; }
}
public class Address
{
public Address
{
}
public int Id { get; set; }
public string Street { get; set; }
public int Number { get; set; }
public int Country { get; set; }
public virtual Customer Customer { get; set; }
}
当我尝试保存它们时,出现以下错误:
Unable to determine the principal end of an association between the types Customer and Address
您需要专门化外键关系。 如此处所述,尝试[ForeignKey("CustomerId")]
在public virtual Customer Customer { get; set; }
和 [ForeignKey("AddressId")]
public virtual Address Address { get; set; }
,并将这些 id 字段添加到模型中。 如:
public class Customer
{
public Customer
{
}
public int Id { get; set; }
public string Name { get; set; }
public int Addressid { get; set; }
[ForeignKey("AddressId")]
public virtual Address Address { get; set; }
}
public class Address
{
public Address
{
}
public int Id { get; set; }
public string Street { get; set; }
public int Number { get; set; }
public int Country { get; set; }
public int CustomerId { get; set; }
[ForeignKey("CustomerId")]
public virtual Customer Customer { get; set; }
}