簡體   English   中英

實體框架一對一關系

[英]Entity framework one to one relation

我首先在實體模型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; } public virtual Customer Customer { get; set; } public virtual Customer Customer { get; set; }[ForeignKey("AddressId")]通過public virtual Address Address { get; set; } public virtual Address Address { get; set; } 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; }              
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM