1

Entity Framework 4.3を使用したASP.NET MVC 4 WEBAPIプロジェクトがあります 私のMS SQLに3つのテーブルがありますDB:ASP.NET MVC 4 WEBAPI Entity Framework 4.3:コレクションから「多対多」を保存する最良の方法

食事 MealCategoryカテゴリ

2番目の表は、(多くの接続に多くの)1と3の接続です。ここ

[Table("Meal")] 
public class Meal 
{ 
[Key] 
public long MealID { get; set; } 
public string MealName { get; set; } 
... 
public virtual ICollection<Category> Categories { get; set; } 
} 

そして、私のカテゴリーのモデルである:私は最初のコードを使用してい

[Table("Category")] 
public class Category 
{ 
[Key] 
public long CategoryID { get; set; } 
... 
public virtual ICollection<Meal> Meals { get; set; } 
} 

が は、ここに私の食事モデルです。そして、DbContextています

public class DgDbContext : DbContext 

{ 
    public DbSet<Category> Category { get; set; } 
    public DbSet<Meal> Meal { get; set; } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Meal>(). 
     HasMany(c => c.Categories). 
     WithMany(p => p.Meals). 
     Map(
     m => 
     { 
      m.MapLeftKey("MealID"); 
      m.MapRightKey("CategoryID"); 
      m.ToTable("MealCategory"); 
     }); 
    } 
} 

はまた、私がアクションを持っている:

// POST /api/<controller>/<action> 
public HttpResponseMessage PostMeals(IEnumerable<Meal> meals) 
{ 
    ... 
} 

そこで質問です:カテゴリーとMealCategoryへのすべての接続でDBにすべての私の食事を保存するための最良の方法は何ですか?

using(var ctx = new DgDbContext()) 
{ 
    foreach(var meal in meals) 
    { 
     ctx.Meal.Add(meal); 
    } 
    ctx.SaveChanges(); 
} 

答えて

0

は、あなたがこのような何かを試してみましたか?