Multiple integrity violation Entity framework 5

Hi, I have 3 classes Person, UserProfile (it inherits Person) and Results, a person can have one or more results when I try to add the result ia for person ai to get the error indicated in the header, my classes are below. 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; } } 

Class 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; } } 

Result class

 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; } } 

Task function

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

Whenever you call this function, I call _ctx.SaveChanges()

I get an error

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

Thanks.

+6
source share
1 answer

Are you trying to add the same Result multiple users?

In this case, it will fail because the entity infrastructure implements the Results collection of the Person class as a foreign key from Results to Persons . The mapping will be the same as if you added the Person navigation property to the Result class.

If you want Person and Result have many-to-many relationships, you need to add the ICollection<Person> Persons property to the Results class to make EF understand this.

+16
source

Source: https://habr.com/ru/post/958267/


All Articles