实体框架一对一关系

时间:2013-10-27 21:11:59

标签: c# entity-framework

我在我的应用程序中使用以下模型,首先使用Entity Framework 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

1 个答案:

答案 0 :(得分:3)

您需要指定外键关系。如上所述[{3}},请尝试在[ForeignKey("CustomerId")]public virtual Customer Customer { get; set; }之上添加[ForeignKey("AddressId")] public virtual Address Address { get; set; }超过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; } } ,并将这些ID字段添加到模型中。如:

{{1}}