多重约束违反了entity framework5

你好我有3个类Person,UserProfile(它inheritance了Person)和Results,一个Person可以有一个或多个结果,当我尝试将ia结果添加到一个人时ai得到标题中提到的错误,我的类是下面的。 任何帮助,将不胜感激。

[Table("People")] public class Person : IPerson { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Name { get { return FirstName + " " + LastName; } set{} } public string Email { get; set; } public DateTime? LastModified { get; set; } public virtual ICollection Results { get; set; } } 

UserProfile类

 [Table("UserProfile")] public class UserProfile : Person { public UserProfile() { Faculty = new Faculty(); Projects = new Collection(); } public string UserName { get; set; } public string CNP { get; set; } public virtual Faculty Faculty { get; set; } public virtual ICollection Projects { get; set; } } 

结果类

 public abstract class Result:INamedEntity { protected Result() { ResultType = new ResultType(); } public int Id { get; set; } public string Name{get;set;} public virtual ResultType ResultType { get; set; } public DateTime? LastModified { get; set; } } 

问题的function

 public void AddResultForUser(int userId, Result result) { _ctx.Users.Single(u => u.Id == userId).Results.Add(result); } 

每次调用此函数后,我都会调用_ctx.SaveChanges()

我得到了一个错误的错误

 Multiplicity constraint violated. The role 'Person_Results_Source' of the relationship 'Repository.Person_Results' has multiplicity 1 or 0..1. 

谢谢。

您是否尝试将相同的Result添加到多个用户?

在这种情况下,这将失败,因为entity framework将实现Person类的Results集合作为从ResultsPersons的外键。 映射将与将Result导航属性添加到Result类时相同。

如果您希望PersonResult具有多对多关系,则必须向Results类添加ICollection Persons属性以使EF理解该属性。