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.
Related
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();
So for various reasons we need to send a large list of Ids to a EF6 query.
queryable.Where(x => list.Contains(x.Id));
is not ideal since it will create a huge were list.
So I was thinking, would it be possible some homehow to pass a table value parameter with the ids and get a IQueryable back that I can join against?
something like (Pseudo code)
var queryable = TableValueToIQueryable<MyTableValueType>(ids);
context.Set<MyEntity>().Join(queryable, x => x.Id, x.Value, (entity, id) => entity);
Is this possible somehow?
update: I have been able to use EntityFramework.CodeFirstStoreFunctions to execute a sql function and map the data to IQueryable<MyEntity>. it uses CreateQuery and ObjectParameters, can I use table value params somehow with ObjectParamters?
update2: Set().SqlQuery(...) will work with Table value parameters, but the resulting DbSqlQuery is not Joinable in SQL with a IQueryably so the result will be two connections and the join is done in memory
var idResult = Set<IdFilter>().SqlQuery("select * from GetIdFilter(#ids)", parameter);
var companies = idResult.Join(Set<tblCompany>(), x => x.Id, y => y.CompanyID, (filter, company) => company).ToList();
update3: ExecuteStoreQuery
((IObjectContextAdapter)ctx).ObjectContext.ExecuteStoreQuery<InvoicePoolingContext.IdFilter>("select * from dbo.GetIdFilter(#ids)", parameter)
.Join(ctx.Set<tblCompany>(), x => x.Id, y => y.CompanyID, (filter, company) => company).ToList();
Gives error:
There is already an open DataReader associated with this Command which
must be closed first.
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();
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));