var topTen = (from ep in db.VisitedCities
join c in db.Countries on ep.PersonWhoVisitedNationalityId equals c.CountryId
join e in db.Cities on ep.CityId equals e.CityId
join t in db.Countries on e.CountryId equals t.CountryId
where t.Name == "Portugal"
select ep.PersonWhoVisitedNationality).ToList();
结果会返回一个包含多个项目的列表但是所有这些项目都是null,我在这里缺少什么?
我希望得到一份国籍清单(它们属于Country
)
提前致谢。
编辑:
好的,所以第一个问题与此有关,我最终想要的是这样的(只有当我把.ToList()
放在中间时才有效:()
var topTen = (from ep in db.VisitedCities
join e in db.Cities on ep.CityId equals e.CityId
join t in db.Countries on e.CountryId equals t.CountryId
where t.Name == "Portugal"
select ep)**.ToList()**
.GroupBy(x => x.PersonWhoVisitedNationality)
.Select(cp => new
{
CountryName = cp.Key,
NumberOfTravelers = cp.Count()
})
.OrderByDescending( x => x.NumberOfTravelers)
.Take(10)
.ToList();
请注意,我正在使用新的实体框架7,我认为现在包含扩展功能还没有...
所以到了夏天,这个查询工作正常,但只有.ToList()
位于中间:(
答案 0 :(得分:0)
好的,因为EF7仍然处于测试阶段并且查询速度非常慢,我最终为EF7创建了一个扩展方法,以便进行原始SQL查询,最终结果如下:
var top10PT = db.Database.ExecuteSqlCommandExtensionMethod(@"
select top 10 Nationality.Name, count(*) AS NumberOfTravelers FROM
(
select [PersonWhoVisitedId] FROM VisitedCity
INNER JOIN City ON VisitedCity.CityId = City.CityId
INNER JOIN Country ON City.CountryId = Country.CountryId
WHERE Country.Alpha2Code = 'PT'
) AS Subquery
INNER JOIN Person ON Person.PersonId = Subquery.PersonWhoVisitedId
INNER JOIN Country as Nationality ON Person.NationalityId = Nationality.CountryId
GROUP BY Nationality.Name
ORDER BY NumberOfTravelers desc
").ToList();
现在它真的很快:D。
这是我的扩展方法,以防有人想知道:
public static class Entity7Extensions
{
public static IEnumerable<dynamic> ExecuteSqlCommandExtensionMethod(this DatabaseFacade database, string sql)
{
var connection = database.GetDbConnection();
var command = connection.CreateCommand();
command.CommandText = sql;
try
{
connection.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
var expandoObject = new ExpandoObject() as IDictionary<string, object>;
for (var i = 0; i < reader.FieldCount; i++)
{
object propertyValue = reader.GetValue(i);
if (propertyValue is System.DBNull)
propertyValue = null;
expandoObject.Add(reader.GetName(i), propertyValue);
}
yield return expandoObject;
}
}
finally
{
connection.Close();
}
}
}