我正在尝试为我的数据库创建代码优先模型,我必须在单个表上创建一个多对多关系,并具有一些其他属性。我的课程如下:
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; }
}
我试图这样做,但每当我尝试从任何模型访问数据时,我都会收到异常。异常消息指出&#34; Contact在数据库中创建循环&#34;并提供InvalidOperationException异常。
请帮我解决这个问题。 谢谢。
答案 0 :(得分:0)
尝试添加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; }
}