我首先使用实体框架代码。我有两个实体:
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();
没有异常或一些想法被抛出。你能告诉我如何删除所有旧的映射条目并在编辑时添加新的条目吗?