首页 > 解决方案 > 实体框架:以多对多关系添加新对象

问题描述

我是 C# 实体框架 (6) 的新手。我创建了三个类 - Country - Area - SubArea

Country 和 Area 之间存在多对多的关系。Area 和 Subarea 之间还有另一种多对多的关系。

一个国家可以包含许多区域,但也有属于多个国家的区域)。区域和子区域也是如此。

我创建了相应的类,并且数据库表已自动创建。CountryAreas 和 SubAreaAreas 的表也已创建,所以一切看起来都不错。外键看起来也不错。

当我创建一个带有相应区域和子区域的新国家对象时,添加到数据库工作正常(参见下面的代码)。

我现在尝试只向现有的 Country 对象添加一个新区域(带有新的子区域),但我不知道这应该如何工作。

事实上,我想添加新的 Area 对象(或数据库条目)并让实体框架更新所有关系(和相应的表)。如果我尝试为现有区域添加新的子区域对象,这同样适用。

任何帮助表示赞赏:-)

public class Country
{
   [Key]
   public string Name { get; set; }
   public List<Area> Areas { get; set; } // virtual enabled lazy loading
 }

public class Area
{
    [Key]
    public string Name { get; set; }
    public virtual List<SubArea> Subareas { get; set; }
    public virtual List<Country> Countries { get; set; }
}

public class SubArea
{
    [Key]
    public string Name { get; set; }
    public virtual List<Area> Areas { get; set; }
}

public class LocationScoutContext : DbContext
{
    public LocationScoutContext()
        : base("name=LocationScout")
    {
    }

    public DbSet<Country> Countries { get; set; }
    public DbSet<Area> Areas { get; set; }
    public DbSet<SubArea> SubAreas { get; set; }

}

// *** this works fine
internal static bool AddCountry(Country newCountry, out string errorMessage)
{
   bool success = true;
   errorMessage = string.Empty;

   try
   {
      using (var db = new LocationScoutContext())
      {
         db.Countries.Add(newCountry);
         db.SaveChanges();
      }
   }
   catch (Exception e)
   {
      errorMessage = BuildDBErrorMessages(e);
      success = false;
   }

   return success;
}

// *** this does not work
internal static bool UpdateCountry(Country upCountry, out string errorMessage)
{
   bool success = true;
   errorMessage = string.Empty;

   try
   {
      using (var db = new LocationScoutContext())
      {
         var country = db.Countries.SingleOrDefault(o => o.Name == upCountry.Name);
         country.Areas = upCountry.Areas;
         db.Entry(country).State = EntityState.Modified;

         var result = db.SaveChanges();
       }
    }
    catch (Exception e)
    {
       errorMessage = BuildDBErrorMessages(e);
       success = false;
    }

    return success;
}

标签: c#entity-frameworklinqentity-framework-6

解决方案


推荐阅读