我正在開發一個ASP.NET MVC項目。我使用實體框架代碼優先與數據進行交互。但我在Code First Approach中建立一對一或零關係時遇到問題。請參閱下面的我的場景。無法在.NET中首先在實體框架代碼中設置一個零或一個關係
這是我的項目類
public class Item
{
public int Id { get; set; }
[MaxLength(90)]
public String ImagePath { get; set; }
[MaxLength(50)]
public String Name { get; set; }
[MaxLength(70)]
public String MmName { get; set; }
[MaxLength(250)]
public String Description { get; set; }
[MaxLength(300)]
public String MmDescription { get; set; }
public int TotalReviewStars { get; set; }
public int TotalReviewCount { get; set; }
public virtual ICollection<Category> Categories { get; set; }
public virtual ICollection<Gallery> Galleries { get; set; }
public virtual ItemContactInfo Contact { get; set; }
}
我想Item類有可選Contact類。所以我在項目類中添加了「public virtual ItemContactInfo Contact」。所以我可以像我的代碼中的「item.Contact」一樣輕鬆地檢索聯繫人。
這是我的聯繫
public class ItemContactInfo
{
public int Id { get; set; }
[MaxLength(50)]
public String GeoLocation { get; set; }
[MaxLength(200)]
public String Address { get; set; }
[MaxLength(250)]
public String MmAddress { get; set; }
[MaxLength(70)]
public String Phones { get; set; }
[MaxLength(70)]
public String MmPhones { get; set; }
[MaxLength(200)]
public String Emails { get; set; }
public int? AreaId { get; set; }
public int ItemId { get; set; }
[ForeignKey("AreaId")]
public virtual Area Area { get; set; }
[ForeignKey("ItemId")]
public virtual Item Item { get; set; }
}
Contact類ItemContactInfo類將有需要的項目。
因此當我運行遷移和更新數據庫時,它在控制檯中給我這個錯誤。
Unable to determine the principal end of an association between the types 'AyarDirectory.Domain.Entities.Item' and 'AyarDirectory.Domain.Entities.ItemContactInfo'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
我該如何解決?
可能的重複[在Fluent API中首先通過Fluent API實現零或一到零或一個關係](http://stackoverflow.com/questions/14701378/implementing-zero-or-one-to-zero-or -one-relationship-in-ef-code-first-by-fluent) –
其他重複:http://stackoverflow.com/q/26389707/861716,但是使用'HasOptional'而不是'HasRequired'。 –