我正在使用實體框架代碼。 我有兩個實體:EF代碼優先編輯對映射實體沒有影響
public class Meal
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int MealID { get; set; }
public virtual List<MealCategory> MealCategories { get; set; }
}
public class MealCategory
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int MealCategoryID { get; set; }
public virtual List<Meal> Meals { get; set; }
}
它們在配置映射:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Meal>()
.HasMany(c => c.MealCategories)
.WithMany(x => x.Meals)
.Map(a =>
{
a.ToTable("MealCategoryMapping");
a.MapLeftKey("MealID");
a.MapRightKey("MealCategoryID");
});
}
當與現有分類它完美地添加新的飯,ID被正確插入映射表
Meal Meal = new Meal();
Meal.MealCategories = new List<MealCategory>();
var categoryToBeAdded = (from x in Context.MealCategoreis where x.MealCategoryID == 1 select x).FirstOrDefault();
Meal.MealCategories.Add(categoryToBeAdded);
MealDataContext.Add(Meal);
MealDataContext.SaveChanges();
但是,如果我嘗試編輯膳食並添加新類別,映射表中不會發生任何事情。舊條目保持不變,新條目不添加。
Meal Meal = (from x in MealDataContext where x.MealID == 1 select x).FirstOrDefault();
Meal.MealCategories = new List<MealCategory>();
var categoryToBeAdded = (from x in Context.MealCategoreis where x.MealCategoryID == 4 select x).FirstOrDefault();
Meal.MealCategories.Add(categoryToBeAdded);
MealDataContext.Attach(entityToUpdate);
MealDataContext.Entry(entityToUpdate).State = EntityState.Modified;
MealDataContext.SaveChanges();
沒有例外或somethink引發。 你能告訴我如何在編輯時刪除所有舊的映射條目並添加新的映射條目嗎?
'entityToUpdate'的作用是什麼? –