Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

c# - Multiplicity constraint violated Entity framework 5

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

The UserProfile class

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

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

The problem function

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

Whenever after calling this function i call _ctx.SaveChanges()

I get the fallowing error

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

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...