【问题标题】:Query many-to-many relationships with Entity Framework使用实体框架查询多对多关系
【发布时间】: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


【解决方案1】:

尝试如下。这将给出所有countries 及其areassubareas

对于 EF 6.x:

using (var db = new LocationScoutContext())
{
   var countries = db.Countries.Include(c => c.Areas.Select(a => a.SubAreas)).ToList();
}

对于 EF Core:

using (var db = new LocationScoutContext())
{
   var countries = db.Countries.Include(c => c.Areas).ThenInclude(a => a.SubAreas).ToList();
}

【讨论】:

  • 请注意ThenIncludeonly supported in EF Core
  • 我刚刚尝试了上面的代码,它给了我一个编译器错误错误 CS1660 无法将 lambda 表达式转换为类型“字符串”,因为它不是委托类型
  • 什么是编译器错误?看看我用的是SubAreas而不是Subareas
  • 错误 CS1660 无法将 lambda 表达式转换为类型“字符串”,因为它不是委托类型 –
  • @BillMiller You probably need using System.Data.Entity; 如果你还没有的话。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-13
  • 2016-12-15
  • 2018-06-26
  • 2017-01-28
  • 2011-12-17
  • 1970-01-01
相关资源
最近更新 更多