Search code examples
entity-frameworksqliteforeign-keysmany-to-manyforeign-key-relationship

How to add entries for many to many relation table with Entity Framework


I have a database with three tables: Word, Idiom, WordIdiom that stores many to many relation between this two tables. WordItem includes only foreign keys for Word and Idiom tables.

After that, I have created Entity model, based on database. I have filled two tables with relevant content, and now I want to add cross-links between these tables.

So, I have written this code:

using (var db = new IdiomsDictionaryEntities())
{
    var allIdioms = from idiom in db.Idioms select idiom;

    foreach (var idiom in allIdioms)
    {
        string[] words = idiom.IdiomText.Split(new[] { " ", "-" }, StringSplitOptions.None);

        foreach (var word in words)
        {
            var wordItem = db.Words.SingleOrDefault(exWord => exWord.WordString.ToLower().Equals(word));
            if (wordItem == null)
            {
                Console.WriteLine("Idiom: " + idiom.IdiomText + ", missing word: " + word);
                continue;
            }

            idiom.Words.Add(wordItem);

            db.SaveChanges();
        }
    }
}

But when I run this code, I'm getting following error:

An unhandled exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll
Additional information: An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.

Inner-inner exception:

Unable to update the EntitySet 'WordIdiomMatch' because it has a DefiningQuery and no element exists in the element to support the current operation.`

As it is my first time with Entity Framework, I'm really don't know how to fix this. I have tried to add [ForeignKey()] property to Entity Framework models, but probably have done it wrong. I have also tried to add a primary key for WordIdiom, but it brakes even more things, as in this case I cannot even add items to Word and Idiom tables.


Solution

  • I have solved the problems, with help of @KerryRandolph and @AntoinePelletier

    I was trying to update entities derived from a many-to-many relationship using Pure Join Table - meaning no other columns except foreign keys are allowed. If you add a Primary Key column to a Join Table, you lose all of the entity framework advantages and have to implement insertion operation manually.

    Proper solution was to alter the join table on the DB to make a PK that includes BOTH of the foreign ID columns.