多重约束违反实体框架5 [英] Multiplicity constraint violated Entity framework 5
问题描述
您好我有3类人,用户配置(它继承人)和结果,一个人可以有一个或多个结果,当我尝试添加IA导致一个人艾得到标题提到的错误,我的班波纹管。任何帮助将是AP preciated。
Hello i have 3 classes Person, UserProfile(it inherits Person) and Results, a Person can have one or more results, when i try to add i a result to a person a i get the error mentioned in the title, my classes are bellow. Any help would be appreciated.
[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<Result> Results { get; set; }
}
该用户配置类
[Table("UserProfile")]
public class UserProfile : Person
{
public UserProfile()
{
Faculty = new Faculty();
Projects = new Collection<Project>();
}
public string UserName { get; set; }
public string CNP { get; set; }
public virtual Faculty Faculty { get; set; }
public virtual ICollection<Project> 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; }
}
问题的功能。
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.
感谢您。
推荐答案
您试图在同一结果
添加到多个用户?
Are you trying to add the same Result
to several users?
在这种情况下,这将失败,因为实体框架将实现结果
的人
类的集合作为一个外国从键结果
到人
。映射将是一样的,如果您有一个人
导航属性添加到结果
类。
In that case this will fail because entity framework will realize the Results
collection of the Person
class as a foreign key from Results
to Persons
. The mapping will be the same as if you add a Person
navigation property to the Result
class.
如果你想人
和结果
有你有添加一个多一对多的关系的ICollection&LT;&人GT;人
属性设置为结果
类,使EF明白这一点。
If you want Person
and Result
to have a many-to-many relationship you have to add a ICollection<Person> Persons
property to the Results
class to make EF understand that.
这篇关于多重约束违反实体框架5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!