2013-10-27 185 views
0

我正在使用實體框架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

回答

3

您需要speicify的外鍵關係。如here所述,嘗試在public virtual Customer Customer { get; set; }[ForeignKey("AddressId")]之上添加[ForeignKey("CustomerId")]而不是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; }    
} 
+0

是的,即解決了這個問題。非常感謝!還有一個問題:我讀到,也可以使用流利的API來實現...並試圖做到這一點:在Customer'HasRequired(c => c.Address).WithRequiredPrincipal(a => a.Customer);'我有爲Address做同樣的事情還是夠了?它的工作原理... – user2818430

+0

它應該用外鍵定義。在我給出的例子中,地址和客戶都保存了一個外鍵,它將需要在雙方。 – pcreech