【发布时间】:2016-05-10 09:40:26
【问题描述】:
我正在开发一个 ASP.NET MVC 项目。我首先使用实体框架代码与数据进行交互。但我在代码优先方法中建立一对零或一关系时遇到问题。
这是我的物品类
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 类。所以我在 Item 类中添加了“public virtual ItemContactInfo Contact”。所以我可以像代码中的“item.Contact”一样轻松检索联系人。
这是我用于联系人的 ItemContactInfo 类
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; }
}
联系人类将具有所需的项目。
所以当我运行迁移和更新数据库时,它在控制台中给了我这个错误。
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.
我该如何解决?
【问题讨论】:
-
其他重复:stackoverflow.com/q/26389707/861716,但使用
HasOptional而不是HasRequired。
标签: .net asp.net-mvc entity-framework ef-code-first entity-framework-migrations