2
votes

I have three classes as shown below (this is an example for my scenario) -

public class A
{
    public int Id {get; set;}
    public virtual C c {get; set;}
}

public class B
{
    public int Id {get; set;}
    public virtual C c {get; set;}
}

public class C
{
    public int AId {get; set;}
    public int BId {get; set;}

    public virtual A a {get; set;}
    public virtual B b {get; set;}
}

AId and BId are foreign keys from respective tables. As there is a one-to-one relationship between A and B and between A and C, I have configured the modelbuilder as -

modelBuilder.Entity<C>().HasRequired(p => p.A).WithRequiredDependent(k => k.C);
modelBuilder.Entity<C>().HasRequired(p => p.B).WithRequiredDependent(k => k.C);

Now, whenever I try to save the changes to C, I am getting an errror like -

"Referential integrity constraint violation. A Dependent Role has multiple principals with different values."

Info1: In my case, A: Id is primary key with databasegeneratedoption.identity. B: Id is a primary key with databasegeneratedoption.none.

Info2: I tried changing WithRequiredDependent to WithOptional, but that didn't work as well.

What can be the issue here?

Update1

As suggested below, I removed AId, BId columns from C, but then started getting this error -

"A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'Id'."

What 'Id' column is mentioned above?

3
What is the primary key of C?Gert Arnold
It's part of the model, just didn't mention here.Sam

3 Answers

0
votes

Try removing properties AId and BId from C, the associations should be enough.

0
votes

You should mark foreign keys explicitly:

public class C
{
    [ForeignKey("A")]
    public int AId {get; set;}
    [ForeignKey("B")]
    public int BId {get; set;}

    public virtual A a {get; set;}
    public virtual B b {get; set;}
}
0
votes

I was receiving the same error but for a different reason. I had a collection of a child class (Students) that was ALSO a collection for another entity (I had two classes with Student collections).

No matter how I annotated the foreign keys, I would receive a 'Referential integrity constraint violation. A Dependent Role has multiple principals with different values' error'. The only solution for me was to remove the Student collection from the 2nd entity.