EF6 code first multiple 1-to-many mapping issue / "Multiplicity" error

jwatts1980

I am receiving the following error when attempting to create the database:

One or more validation errors were detected during model generation:

Interaction_CauseElement_Source: : Multiplicity is not valid in Role 'Interaction_CauseElement_Source' in relationship 'Interaction_CauseElement'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.

Interaction_EffectElement_Source: : Multiplicity is not valid in Role 'Interaction_EffectElement_Source' in relationship 'Interaction_EffectElement'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.

I've seen this error in other Stack Overflow posts, but in the examples I found, the OP was trying for a 1-to-1 relationship in both directions between the tables. That is not what I am looking for.

Here is my model:

public class Element
{
    [Key]
    public int ID { get; set; }

    [Required, MaxLength(64)]
    public string Name { get; set; }

    [MaxLength(200)]
    public string Description { get; set; }
}

public class Interaction
{
    [Key]
    public int ID { get; set; }

    [Index, Required]
    public int CauseID { get; set; }

    [Index, Required]
    public int EffectID { get; set; }

    [MaxLength(64)]
    public string Location { get; set; }    

    [ForeignKey("CauseID")]
    public virtual Element CauseElement { get; set; }

    [ForeignKey("EffectID")]
    public virtual Element EffectElement { get; set; }
}

Items in the Elements table are unique. A pair of elements can interact with each other in any number of locations. The CauseID/EffectID pair is not going to be unique.

The only other place I am changing the model is in the OnModelCreating method. I had received this error:

Introducing FOREIGN KEY constraint 'FK_dbo.Interactions_dbo.Elements_Cause' on table 'Interactions' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint. See previous errors.

And had to create a cascade policy for the model. This code fixed that error:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    //Prevent cyclic cascade on elements table
    modelBuilder.Entity<Interaction>()
        .HasRequired(i => i.CauseElement)
        .WithRequiredDependent()
        .WillCascadeOnDelete(false);
    modelBuilder.Entity<Interaction>()
        .HasRequired(i => i.EffectElement)
        .WithRequiredDependent()
        .WillCascadeOnDelete(false);

    base.OnModelCreating(modelBuilder);
}

But then I received the cryptic "Multiplicity" error. It seems like it wants me to make public virtual Element CauseElement into a collection like public virtual ICollection<Element> CauseElement, but that would not properly model the relationship.

jwatts1980

I found the solution. This article on EntityFrameworkTutoral.net helped out. Because I need TWO references from the Interaction class to the Element class, this relationship is too complex to model in EF with only the attributes.

I had to update the model and then use the fluent API to tell EF how to treat the relationships. I updated my model to the following:

public class Element
{
    public Element()
    {
        CauseElements = new List<Interaction>();
        EffectElements = new List<Interaction>();
    }

    [Key]
    public int ID { get; set; }

    [Required, MaxLength(64)]
    public string Name { get; set; }

    #region Navigation

    public virtual ICollection<Interaction> CauseElements { get; set; }
    public virtual ICollection<Interaction> EffectElements { get; set; }

    #endregion
}

public class Interaction
{
    [Key]
    public int ID { get; set; }

    [Index]
    public int CauseID { get; set; }

    [Index]
    public int EffectID { get; set; }

    [MaxLength(64)]
    public string Location { get; set; }

    #region Navigation

    [ForeignKey("CauseID")]
    public virtual Element CauseElement { get; set; }

    [ForeignKey("EffectID")]
    public virtual Element EffectElement { get; set; }

    #endregion
}

And in my DbContext class I used the fluent API to create the link between the Interaction.CauseElement and Element.CauseElements and which property was the foreign key for the Interaction table (and the same with the Effect relationship):

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    //Prevent cyclic cascade on elements table
    modelBuilder.Entity<Interaction>()
        .HasRequired(i => i.CauseElement)
        .WithRequiredDependent()
        .WillCascadeOnDelete(false);
    modelBuilder.Entity<Interaction>()
        .HasRequired(i => i.EffectElement)
        .WithRequiredDependent()
        .WillCascadeOnDelete(false);

    //Create the links between the element, the key, and the collection
    modelBuilder.Entity<Interaction>()
        .HasRequired<Element>(i => i.CauseElement)
        .WithMany(e => e.CauseElements)
        .HasForeignKey(i => i.CauseID);
    modelBuilder.Entity<Interaction>()
        .HasRequired<Element>(i => i.EffectElement)
        .WithMany(e => e.EffectElements)
        .HasForeignKey(i => i.EffectID);

    base.OnModelCreating(modelBuilder);
}

It seems that Entity Framework tries to automatically infer the relationships between the tables when you have a simple 1-to-many relationship. If I removed EffectElement from the Interaction class (and EffectElements from Element), EF was able to create the relationship easily. But when I added it back, I received the error again.

Since that Element type showed up twice in the Interaction class, it didn't know how to create the relationship. I had to explicitly define it in the OnModelCreating method.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Creating a many-to-many relationship in EF6 code first

分類Dev

EF6 Code First and mapping via annotations, how do I build the configuration?

分類Dev

EF Code first 1 to 1 relationship error

分類Dev

Set EF6 Code First strings fluently to nvarchar(max)

分類Dev

Functional grouping in DbContext for EF6 using FluentAPI and Code First

分類Dev

EF6 mapping many-to-many using same column name

分類Dev

Code-First Entity Framework Multiple Collections with Many to Many

分類Dev

Multiplicity is not valid in Role 1..* OR EF weird migration code OR how to store two separate sets of completely different users in one DB

分類Dev

Add additional column to existing many to many relationship - EF Code First

分類Dev

EF6 Code First Migration com um único banco de dados de contexto múltiplo

分類Dev

EF6 Code First in WPF create local DB in application folder

分類Dev

EF Code First, Model First or Db First? for a many changing medium-large app

分類Dev

How to build a many-to-many relation between a model and an enum, in EF code first?

分類Dev

EF Code First many-to-many: how to specify name of th third table and add some other properties to it?

分類Dev

EF Core Many to Many Issue Dual Types

分類Dev

私のSeed()メソッドがCode First EF6で呼び出されることはありません

分類Dev

Using Effort with EF6 in a DB First approach

分類Dev

Automapper many to many mapping

分類Dev

EF6 Database First - EF trying to create my database (but all tables already exist)

分類Dev

Code First Entity Framework 6:複合キーを使用して1対1

分類Dev

Problem with EF-Core Code first throwing error because of backing field

分類Dev

Bidirectional Many to One Mapping

分類Dev

React mapping rendering issue

分類Dev

Hibernate Inheritance mapping issue

分類Dev

Linq to Entity - error on ICollection<Guid> (code first)

分類Dev

Query annotation count of list for many to many mapping

分類Dev

EF Code First Navigation Property to same table

分類Dev

EF Code First Foreign Key Same Table

分類Dev

EF reverse engineering code first and stored procedures

Related 関連記事

  1. 1

    Creating a many-to-many relationship in EF6 code first

  2. 2

    EF6 Code First and mapping via annotations, how do I build the configuration?

  3. 3

    EF Code first 1 to 1 relationship error

  4. 4

    Set EF6 Code First strings fluently to nvarchar(max)

  5. 5

    Functional grouping in DbContext for EF6 using FluentAPI and Code First

  6. 6

    EF6 mapping many-to-many using same column name

  7. 7

    Code-First Entity Framework Multiple Collections with Many to Many

  8. 8

    Multiplicity is not valid in Role 1..* OR EF weird migration code OR how to store two separate sets of completely different users in one DB

  9. 9

    Add additional column to existing many to many relationship - EF Code First

  10. 10

    EF6 Code First Migration com um único banco de dados de contexto múltiplo

  11. 11

    EF6 Code First in WPF create local DB in application folder

  12. 12

    EF Code First, Model First or Db First? for a many changing medium-large app

  13. 13

    How to build a many-to-many relation between a model and an enum, in EF code first?

  14. 14

    EF Code First many-to-many: how to specify name of th third table and add some other properties to it?

  15. 15

    EF Core Many to Many Issue Dual Types

  16. 16

    私のSeed()メソッドがCode First EF6で呼び出されることはありません

  17. 17

    Using Effort with EF6 in a DB First approach

  18. 18

    Automapper many to many mapping

  19. 19

    EF6 Database First - EF trying to create my database (but all tables already exist)

  20. 20

    Code First Entity Framework 6:複合キーを使用して1対1

  21. 21

    Problem with EF-Core Code first throwing error because of backing field

  22. 22

    Bidirectional Many to One Mapping

  23. 23

    React mapping rendering issue

  24. 24

    Hibernate Inheritance mapping issue

  25. 25

    Linq to Entity - error on ICollection<Guid> (code first)

  26. 26

    Query annotation count of list for many to many mapping

  27. 27

    EF Code First Navigation Property to same table

  28. 28

    EF Code First Foreign Key Same Table

  29. 29

    EF reverse engineering code first and stored procedures

ホットタグ

アーカイブ