[英]Get data from nested table using entity framework
First of all this is my first question in the forum so please excuse me for any writing mistake. 首先,这是我在论坛上的第一个问题,因此对任何写作错误都请原谅。
I have 4 tables 我有4张桌子
attaching the table diagram 附表图
What I want is to get list of attraction name joining 'tblattraction' with 'tblattractionmaster' and count of the exact attraction for each place from 'tblattractions' using 'locationid' , I am using entity framework but don't know how to do that, 我想要的是使用“ locationid”获取连接“ tblattraction”和“ tblattractionmaster”的景点名称列表以及“ tblattractions”中每个地方的确切景点数量,我正在使用实体框架,但不知道该怎么做,
Disclaimer: Each location can consist Multiple Places Each Place can consist Multiple Attractions 免责声明:每个地点可以包含多个地点每个地点可以包含多个景点
What I have tried 我尝试过的
return context.tblLocationMasters.Select(t => new details()
{
locationid = t.LocationId,
locationname = t.LocationName,
attractions =t.tblPlaces.SelectMany(a => a.tblAttractions).Select(b => new attractions(){
AttractionName=b.tblAttractionMaster.attractionname//(Not working),
TotalAttractions=0//???
}).ToList()
}).ToList();
I recreated your model (slightly different) using Code First. 我使用Code First重新创建了您的模型(略有不同)。 I came up with the following structure:
我想出了以下结构:
public class Location
{
public int LocationId { get; set; }
public string LocationName { get; set; }
public ICollection<Place> Places { get; set; }
}
public class Place
{
public int PlaceId { get; set; }
public string PlaceName { get; set; }
public int LocationId { get; set; }
public Location Location { get; set; }
public ICollection<AttractionPlace> Attractions { get; set; }
}
public class Attraction
{
public int AttractionId { get; set; }
public string AttractionName { get; set; }
}
public class AttractionPlace
{
public int AttractionPlaceId { get; set; }
public int PlaceId { get; set; }
public Place Place { get; set; }
public int AttractionId { get; set; }
public Attraction Attraction { get; set; }
}
Then, I could get the results in the way you needed with the following query: 然后,可以通过以下查询以所需的方式获得结果:
var query = (from loc in db.Locations
join pla in db.Places.Include(x => x.Attractions) on loc.LocationId equals pla.LocationId
let count = pla.Attractions.Count()
select new
{
loc.LocationId,
loc.LocationName,
Attractions = pla.Attractions.Select(z => new
{
pla.PlaceName,
z.AttractionId,
z.Attraction.AttractionName
}),
AttractionsByPlaceCount = count
});
The query above returns data in this format 上面的查询以这种格式返回数据
Just a side note though: I didn't went further to see the performance of this query. 不过 ,请注意:我没有进一步了解此查询的性能。 The SQL generated by Linq wasn't that bad, but you should consider analyzing it before actually using it in production.
Linq生成的SQL还不错,但是您应该在实际将其用于生产之前考虑对其进行分析。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.