ibrahim genc

ibrahim genc

  • NA
  • 16
  • 475

Many to many table insert problem in MVC-Code First

Jul 8 2019 5:01 AM
Yesterday I asked a question and later I say solved the problem. But today the same error occurred again.

I have three tables `dbo.Food`, `dbo.Menu` and `dbo.FoodMenu` which is the many-to-many link table - like this:

* dbo.Food { ID, FoodName }
* dbo.Menu { ID, MenuName }
* dbo.FoodMenu  { FoodID, MenuID }

I want to insert Food id and Menu id into FoodMenu table. My context is ok, my mapping is ok, codes and `Exception` below. Please help.

    public JsonResult FoodMenu(FoodMenuViewModel vm)
    {
        if (ModelState.IsValid)
        {
            ManyDbContext ctx = new ManyDbContext();

            foreach (var item in vm.MenuIds)
            {
                ctx.FoodMenus.Add(new FoodMenu { FoodID = vm.FoodId, MenuID = item });
                ctx.SaveChanges();
            }
   
            return Json(new { Result = true, Mesaj = "" });
        }
        else
        {
            return Json(new { Result = false, Mesaj = "" });
        }
    }

Exception:

> System.Data.Entity.Infrastructure.DbUpdateException: 'An error occurred while updating the entries. See the inner exception for details.' 
> SqlException: Invalid object name '**dbo.FoodMenus**'. 
 
Context:

            public DbSet<Food> Foods { get; set; }
            public DbSet<Menu> Menus { get; set; }
            public DbSet<FoodMenu> FoodMenus { get; set; }

Mapping:

    modelBuilder.Entity<Food>()
                .HasMany<Menu>(s => s.menus)
                .WithMany(c => c.foods)
                .Map(cs =>
                {
                    cs.MapLeftKey("FoodID");
                    cs.MapRightKey("MenuID");
                    cs.ToTable("FoodMenu");
                });

What I understand from this error is: my table's name is `dbo.FoodMenu` but exception says: it must be `dbo.FoodMenus`. Yet I don't know why.

Answers (6)