I want to order my projects by the last generated timestamp:
var projectsOrderd = projects.OrderBy(r => r.Timestamps.Select(t => t.End));
but there is an error:
"DbSortClause expressions must have a type that is order comparable"
type of End: datetime
is there any solution?
ps: runnig the statment on the SQL-Server works fine
You cant sort by a collection (EG a .Select())
Perhaps you want something like
var projectsOrderd = projects.OrderBy(r => r.Timestamps.Max(t => t.End));
or
var projectsOrderd = projects.OrderBy(r => r.Timestamps.FirstOrDefault(t => t.End));
Related
I'm using Entity Framework core 6 with SQL Server. I have the following query:
dbContext.Table1
.Where(t1 => some_condition(t1.some_property))
.Select(t1 => new
{
Field1 = t1.some_property,
Field2 = dbContext.Table2.Where(t2 => some_condition(t1.some_property, t2.some_property)).First(), // <-- this is my question
});
The thing is that this subquery dbContext.Table2.Where(t2 => some_condition(t1, t2)).First(), is used in many other places. I need to extract it somehow and call it instead of copy-pasting it everywhere.
I tried to extract it in a function like this:
public string Get(string some_property) => context.Table2
.Where(t => some_condition(some_property, t.some_property))
.First();
dbContext.Table1
.Where(t1 => some_condition(t1.some_property))
.Select(t1 => new
{
Field1 = t1.some_property,
Field2 = Get(t1.some_property)
});
But with that I get the subquery to execute separately and for every element in the collection (N+1 problem. I was expecting it though).
Is there a way to achieve that ? maybe using expression trees (which I'm not yet very familiar with).
I am trying to build a query using asp.net core c#
https://www.reflectionit.nl/blog/2017/paging-in-asp-net-core-mvc-and-entityframework-core
I trying to do a filtering however I need the data from another table which have my unique id
var result = _context.UserRoles.Where(y => y.RoleId.Contains(selectedRoles.Id)); // Retrieve the the userid i have from another table with the selected roleid
var query = _context.Users.Where(x => //I have already tried contains, where join );
If there is a site where i can learn this query please recommend. "Join()" does not work as I am doing paging
a least two solutions (please note that I do not check the identity classes members, so the following is the "spirit" of the solution (you miss the select clauses) ):
var result = _context.UserRoles.
Where(y => selectedRoles.Contains(y.RoleId)).
Select(y => y.User);
or
var result = _context.UserRoles.
Where(y => selectedRoles.Contains(y.RoleId)).
Select(y => y.UserId);
query = _context.Users.
Where(x => result.Contains(x.Id));
That said, assuming that there is no UserRoles table exposed in Identity (v2), you probably want:
userManager.Users.
Where(u => u.Roles.Any(r => selectecRoles.Contains(r.RoleId)));
Up to you to instanciate the userManager.
Is there a proper way to do Count of child items of an entity and filter by this value
The way i'm trying to do it right now
var seed = context.Items.Select(x => new {
count = x.ChildItems.Count()
};
seed = seed.Where(x => x.count > 0);
As a result I see in logs that
The LINQ expression '...' could not be translated and will be evaluated locally.
And it will create count query for each row!!
Am i doing something wrong or this is not possible in EF CORE 2.1
What's wrong with the following:
var seed = context.Items.Include(x => x.ChildItems).Where(x => x.ChildItems.Count() > 0).ToList();
I'm trying to count some records that were updated this week and group them by the day of week (depending when they were last updated). E.g.So Tues:1, Thur:4 Fri:5 etc... I'm not sure how to group by day of week.
var data = repo
.Where(o => o.LastUpdated >= monday)
.GroupBy(o => o.LastUpdated)
.Select(g => new { DayOfWeek = g.Key, Count = g.Count() })
.ToList();
I've tried .GroupBy(o => o.LastUpdated.DayOfWeek but that throws an error :
"The specified type member 'DayOfWeek' is not supported in LINQ to Entities"
If you are targeting only SqlServer database type, you can use SqlFunctions.DatePart canonical function like this
var data = repo
.Where(o => o.LastUpdated >= monday)
.GroupBy(o => SqlFunctions.DatePart("weekday", o.LastUpdated))
.Select(g => new { DayOfWeek = g.Key, Count = g.Count() })
.ToList();
Unfortunately there is no such general canonical function defined in DbFunctions, so if you are targeting another database type (or multiple database types), the only option is to switch to Linq To Objects context as described in another answer.
The message is explicit, Entity Framework doesn't know how to translate "DayOfWeek" to SQL. The simplest solution would be to do the grouping outside of SQL after retrieving the data:
var data = repo
.Where(o => o.LastUpdated >= monday)
.AsEnumerable() // After this everything uses LINQ to Objects and is executed locally, not on your SQL server
.GroupBy(o => o.LastUpdated)
.Select(g => new { DayOfWeek = g.Key, Count = g.Count() })
.ToList();
It should hardly have a performance impact either way as you're not filtering further down so you're not retrieving more data than you need from the server, anything past AsEnumerable is materialized as data, anything before just générâtes a SQL query, so past AsEnumerable (or anything else that would materialize the query like ToArray or ToList) you can use anything you'd normally use in C# without worrying about it being translatable to SQL.
It is only possible to lastupdated column datatype of datetime.
var data = repo.Where(o => o.LastUpdated >= monday).AsEnumerable().GroupBy(o => o.LastUpdated.Value.Day).Select(g => new { DayOfWeek = g.Key, Count = g.Count() }).ToList();
how to select distinct with paging in entity framework?
i try to code below
var ll = _ctx.Cwzz_AccVouchMain.Select(v => v.Ddate).Distinct();
var l = ll.Skip(start).Take(limit).ToList();
but error:
must call orderBy method before skip
but my try
var ll = _ctx.Cwzz_AccVouchMain.Select(v => v.Ddate).Distinct();
var l = ll.OrderBy(v => v.Year).ThenBy(v => v.Month).ThenBy(v => v.Date).Skip(start).Take(limit).ToList();
error
ystem.NotSupportedException: LINQ to Entities not suppor type of "Date”。only support initial settlement,entity memeber,entity navagation property.
how to do?
Try this instead :
var ll = _ctx.Cwzz_AccVouchMain.Select(v => v.Ddate).Distinct();
var l = ll.OrderBy(v => v).Skip(start).Take(limit).ToList();
When you try to order by year, month and date, your query is not yet executed, and when .ToList() triggers it, it tries to build the appropriate sql query before sending it to your database server. However, your db has no clue about a Ddate.Year, Ddate.Month or Ddate.Date, because on the db side the Ddate field is a simple date, he doesn't understand your object with properties like the DateTime you use in C#.
If you wanted to order by month only (for example), you would have to trigger your query before that.