I'm trying to make a one-to-many mapping, but I have some difficulties on saving updates.
Menu can have 0 to 1 module.
Module can have 0 to many menus.
When i make a new menu object and saves it, the module is saved into the db, but on update it isn't.
This is working:
var menu = new Menu()
menu.Title = "Menu Title";
menu.Module = repository.GetModule(2);
...
DbContext.SaveChanges()
...
Saves the menu item with the foreign key to the Module.
MenuID : 1
ModuleID : 2
When i'm trying to make an update like this:
var menu = repository.GetMenu(1);
menu.Module = repository.GetModule(3);
Edit: ... DbContext.SaveChanges() ...
The ModuleID in the Menu table isn't changed. What is wrong?
My model:
public class Menu
{
[Key]
public int MenuID { get; set; }
public string Title { get; set; }
public int ModuleID { get; set; } <-- Is this necessary
public virtual Module Module { get; set; }
}
public class Module
{
[Key]
public int ModuleID { get; set; }
public string Name { get; set; }
public virtual ICollection<Menu> Menus { get; set; }
}
Mapping:
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
modelBuilder.Entity<Module>().HasMany<Menu>(m => m.Menus).WithOptional().HasForeignKey(m => m.ModuleID);
}
To get my mapping working I had to add the ModuleID to the Menu class, but can I map this different?
Edit:
I'm using MySQL
Menu table:
int MenuID
varchar Title
int ModuleID
Module table:
int ModuleID
varchar Name
Finally i figured it out. It was a stupid noob error:
public ActionResult Edit(int id, MenuModel menu)
{
var menuDb = repository.Get(id);
TryUpdateModel(menuDb);
//repository.save(menu); <-- WRONG!
repository.save(menuDb); <-- BINGO... It works!
}