【问题标题】:Cannot set one to zero-or-one relationship in Entity Framework code first in .NET无法在 .NET 中首先在实体框架代码中设置一对零或一的关系
【发布时间】: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.

我该如何解决?

【问题讨论】:

标签: .net asp.net-mvc entity-framework ef-code-first entity-framework-migrations


【解决方案1】:

这可能是一个循环引用,因为您在每个模型中都有指向彼此的属性。项目 项目联系信息。去掉 Item 模型中的 Contact 属性。

ItemContactInfo 表中的 ItemId 需要作为键和外键来强制执行 0 或 1 关系。

【讨论】:

  • 这肯定不是问题。\
  • @WaiYan EF 无法确定主体端,因为错误状态。这是因为两个模型相互指向,而 EF 无法弄清楚。
  • 奥普斯。对不起,我回答了不同的问题。是的,我把它改成了一对多的关系。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-08
  • 1970-01-01
  • 1970-01-01
  • 2013-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多