【问题标题】:ASP.NET MVC 4 WEBAPI Entity Framework 4.3: What is the best way to save "many to many" from CollectionASP.NET MVC 4 WEBAPI Entity Framework 4.3:从集合中保存“多对多”的最佳方法是什么
【发布时间】:2012-04-25 17:55:41
【问题描述】:

我有一个带有 Entity Framework 4.3 的 ASP.NET MVC 4 WEBAPI 项目 它在我的 MS SQL DB 中有 3 个表:

膳食 膳食类别 类别

第二个表是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)
{
  ...
}

所以问题是:将我所有的餐点保存到 DB 并连接到 Category 和 MealCategory 的最佳方法是什么?

【问题讨论】:

    标签: ef-code-first many-to-many asp.net-mvc-4 asp.net-web-api entity-framework-4.3


    【解决方案1】:

    你有没有尝试过这样的事情:

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

    ?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多