.NET EF4 duplicating entities on save
I'm using MVC3 & EF4, running into a bit of a problem when trying to save an entity with foreign key relations.
Here's my models (shortened to save space)
public class MenuItem
{
/// <summary>
/// The ID
/// </summary>
[Key]
public int MenuItemID { get; set; }
/// <summary>
/// Foreign key to menu item category
/// </summary>
public int MenuItemCategoryID { get; set; }
/// <summary>
/// The item category
/// </summary>
public MenuItemCategory MenuItemCategory { get; set; }
}
public class MenuItemCategory
{
/// <summary>
/// The ID
/// </summary>
[Key]
public int MenuItemCategoryID { get; set; }
/// <summary>
/// The name
/// </summary>
[Required]
[DataType(DataType.Text), StringLength(128)]
public string Name { get; set; }
}
Then I have this method in my repository which saves MenuItems:
public void CreateMenuItem(MenuItem menuItem)
{
MissChuDataContext.MenuItems.Add(menuItem);
MissChuDataContext.SaveChanges();
}
My database mapping is:
modelBuilder.Entity<MenuItem>().HasRequired(x => x.MenuItemCategory).WithMany().HasForeignKey(x => x.MenuItemCategoryID);
However for some reason the repo method creates duplicate MenuItemCategory entities when saving a new MenuItem which is related to an existing MenuItemCategory.
I have managed to get it working by reassigning the MenuItemCategory from the context in the controller:
[HttpPost]
public ActionResult CreateMenuItem(MenuItem menuItem)
{
menuItem.MenuItemCategory = MenuItemRepository.GetMenuItemCategoryByID(menuItem.MenuItemCategory.MenuItemCategoryID);
MenuItemRepository.CreateMenuItem(menuItem);
return View();
}
This works and doesn't create a duplicate MenuItemCategory, however I'm sure I'm missing something simple which would p开发者_StackOverflow中文版revent the duplication and without me having to use the menuItem.MenuItemCategory = ... call in the controller.
Have looked EVERYWHERE but found nothing that works so far :(
Many thanks!
Try this:
public void CreateMenuItem(MenuItem menuItem)
{
MissChuDataContext.MenuItems.Add(menuItem);
MissChuDataContext.Entry(menuItem.MenuItemCategory).State = EnttiyState.Unchanged;
MissChuDataContext.SaveChanges();
}
The problem is that when you call Add
EF adds all entities in the object graph not only the menuItem. You must always manually handle state of all entities attached or added to your context when you don't load them by the same context instance before you do any changes.
精彩评论