开发者

EF CTP5 mapping fails on update

开发者 https://www.devze.com 2023-02-14 04:10 出处:网络
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.

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 Modul开发者_运维技巧eID

Module table:

int ModuleID

varchar Name


In your second example I assume you left the .SaveChanges() out of the code snippet?

Your class structure and mapping look correct, have you hooked up a SQL Profiler to see what command is being executed by the second examples .SaveChanges()?


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! 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消