【问题标题】:many-to-many relationship on single table using code first with additional properties使用带有附加属性的代码优先在单个表上建立多对多关系
【发布时间】:2017-10-22 15:27:00
【问题描述】:

我正在尝试为我的数据库创建一个代码优先模型,我必须在具有一些附加属性的单个表上创建多对多关系。我的课程如下:

public class Contact
{
    [Key, Column(Order = 1)]
    [ForeignKey("User")]
    public Guid Owner { get; set; }
    [Key, Column(Order = 2)]
    [ForeignKey("User")]
    public Guid UserID { get; set; }
    [MaxLength(50)]
    public string FirstName { get; set; }
    [MaxLength(50)]
    public string LastName { get; set; }

    // Navigation properties
    public User User { get; set; }
    public User User1 { get; set; }
}

我的 User 类现在相当简单,但看起来像这样:

public class User
{
    public Guid ID { get; set; }
    [MaxLength(50)]
    public string Email { get; set; }
    [MaxLength(50)]
    public string FirstName { get; set; }
    [MaxLength(50)]
    public string LastName { get; set; }

    public List<Contact> Owner { get; set; }
    public List<Contact> Contacts { get; set; }
}

这就是我尝试这样做的方式,但是每当我尝试从任何模型访问数据时都会出现异常。异常消息指出“联系人在数据库中创建循环”并给出 InvalidOperationException 异常。

请帮我解决这个问题。 谢谢。

【问题讨论】:

    标签: asp.net asp.net-web-api ef-code-first


    【解决方案1】:

    尝试添加InversePropertyAttribute,同时修复其余代码:

    public class Contact
    {
        //other properties...
    
        [Key, Column(Order = 1)]
        [ForeignKey("User")]
        public Guid Owner { get; set; }
        [Key, Column(Order = 2)]
        [ForeignKey("User1")]
        public Guid UserID { get; set; }
    
        public virtual User User { get; set; }
        public virtual User User1 { get; set; }
    }
    
    public class User
    {
        //other properties...
    
        [InverseProperty("User")]
        public virtual ICollection<Contact> Owner { get; set; }
        [InverseProperty("User1")]
        public virtual ICollection<Contact> Contacts { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-16
      • 1970-01-01
      • 2013-03-14
      相关资源
      最近更新 更多