繁体   English   中英

使用实体框架查询多对多关系

[英]Query many-to-many relationships with Entity Framework

我是C#实体框架的新手。 我创建了三个类-国家-区域-分区

国家与地区之间存在多对多关系。 区域和子区域之间还有另一对多关系。

一个国家/地区可以包含多个区域,但是也可以包含多个国家/地区所属的区域。 区域和子区域相同。

我创建了各自的类,并且数据库表已自动创建。 也已经创建了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);
}

我尝试了如上所示的操作,但是显然没有进行任何连接,只是给了我具有空区域和分区的国家的名称。

任何帮助表示赞赏:-)

尝试如下。 这将使所有具有其areassubareascountries

对于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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM