c# - 实体框架:以多对多关系添加新对象
问题描述
我是 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;
}
解决方案
推荐阅读
- javascript - 自第二次请求以来,AJAX 成功无法正确呈现
- ms-access - 如何正确创建 SQL 查询
- c++ - 这是词法分析器的代码,谁能详细解释一下这段代码?
- python - 如何修复 TypeError: +: 'int' 和 'str' 不支持的操作数类型
- .net - 可以使用不是长期运行的任务的长期任务吗?
- c# - 使用协程设置进行 PlayMode 测试
- python - 根据另一个数据框中的行条件,在一个数据框中查找值
- python - Django 服务器无法访问
- javascript - 如何替换src domian tld
- r - 将递归向量更改为原子向量以进行 t 检验