【发布时间】:2019-01-16 23:45:42
【问题描述】:
我是 C# 实体框架的新手。我创建了三个类 - 国家 - 区域 - 分区
Country 和 Area 之间存在多对多的关系。 Area 和 Subarea 之间还有另一种多对多的关系。
一个国家可以包含多个区域,但也有属于多个国家的区域)。区域和子区域相同。
我创建了相应的类,并且数据库表已自动创建。 CountryAreas 和 SubAreaAreas 的表也已创建,所以一切看起来都不错。外键看起来也不错。
我可以通过(见下文)将数据写入表格。
我现在正在努力从数据库中选择具有相应区域和子区域的所有国家/地区。
我阅读了几篇文章,看起来我缺乏关于 LINQ 查询和实体框架的基本知识。
public class Country
{
#region attributes
[Key]
public string Name { get; set; }
public List<Area> Areas { get; set; } // virtual enabled lazy loading
#endregion
}
public class Area
{
#region attributes
[Key]
public string Name { get; set; }
public virtual List<SubArea> Subareas { get; set; }
public virtual List<Country> Countries { get; set; }
#endregion
}
public class SubArea
{
#region attributes
[Key]
public string Name { get; set; }
public virtual List<Area> Areas { get; set; }
#endregion
}
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; }
}
// *** reading the data works fine ***
using (var db = new LocationScoutContext())
{
db.Countries.Add(newCountry);
db.SaveChanges();
}
// *** I tried this ***
var allCountries = new List<Countries>();
using (var db = new LocationScoutContext())
{
var query = from c in db.Countries select c;
}
foreach (var c in query)
{
allCountries.Add(c);
}
我尝试了如上所示的方法,但这显然没有进行任何连接,只是给了我带有空区域和子区域的国家/地区的名称。
任何帮助表示赞赏:-)
【问题讨论】:
-
旁注:您不需要从查询中一一添加国家/地区。
allCounties = db.Countries.ToList();会很好。
标签: c# entity-framework linq