繁体   English   中英

无法在 .NET 中首先在实体框架代码中设置一到零或一的关系

[英]Cannot set one to zero-or-one relationship in Entity Framework code first in .NET

我正在开发一个 ASP.NET MVC 项目。 我使用 Entity Framework Code First 与数据交互。 但是我在 Code First Approach 中建立一对零或一的关系时遇到了问题。

这是我的项目类

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.

我该如何解决?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM