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();
The result of this returns a list with several items but all of them are null, what im i missing here?
I am expecting to get a list of nationalities (they are of type Country
)
Thanks in advance.
EDIT :
Ok so the first question was related to this, what i want in the end is something like this (which works but only if I put the .ToList()
in the middle :( )
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();
Note that I am using the new entity framework 7 and I think for now the include extention does not work yet... So to summer up this query works fine but only if the .ToList()
is in the middle :(
Ok so since EF7 is still in beta and the query was super slow i ended up creating an extension method for EF7 in order to do raw SQL query's and ended up like this :
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();
Now it's really fast :D.
Here's my extension method in case anyone is wondering :
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();
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.