2015-08-09 32 views
0
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(); 

这样做的结果返回一个列表与几个项目,但他们都是空的,即时我在这里失踪?如何让这个linq查询返回正确的值

我期待获得国籍的名单(他们是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,我觉得对于现在的包括extention还不所以夏季工作... 了此查询工作正常,但只有当.ToList()在中间:(

+0

你可以返回“C”,而不是“ep.PersonWhoVisitedNationality”。我认为它应该工作。 –

回答

0

好了,所以既然EF7仍处于测试阶段,并查询是超级慢我结束了才能做原始的SQL查询的创建EF7的扩展方法,并弄成这个样子:

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