你好我有3个类Person,UserProfile(它继承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<Result> Results { get; set; }
}
UserProfile类
[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.
谢谢。
答案 0 :(得分:19)
您是否尝试向多个用户添加相同的Result
?
在这种情况下,这将失败,因为实体框架将Results
类的Person
集合实现为从Results
到Persons
的外键。映射将与向Person
类添加Result
导航属性相同。
如果您希望Person
和Result
拥有多对多关系,则必须向ICollection<Person> Persons
类添加Results
属性,以使EF了解该属性