I want to do DB query with EF. The LINQ expression 'DbSet() and the query look slike
.Where(p => p.SellerCustomerId == __sellerId_0)
.Where(p => p.Quantity > 0)
.Join(
inner: DbSet<Product>(),
outerKeySelector: p => EF.Property<long?>(p, "ProductId"),
innerKeySelector: p0 => EF.Property<long?>(p0, "Id"),
resultSelector: (o, i) => new TransparentIdentifier<ProductInstance, Product>(
Outer = o,
Inner = i
))
.Where(p => (bool)DbSet<ProductCategory>()
.Where(p1 => EF.Property<long?>(p.Inner, "Id") != null && object.Equals(
objA: (object)EF.Property<long?>(p.Inner, "Id"),
objB: (object)EF.Property<long?>(p1, "ProductId")))
.Join(
inner: DbSet<Category>(),
outerKeySelector: p1 => EF.Property<long?>(p1, "CategoryId"),
innerKeySelector: c => EF.Property<long?>(c, "Id"),
resultSelector: (o, i) => new TransparentIdentifier<ProductCategory, Category>(
Outer = o,
Inner = i
))
.Where(p1 => p1.Inner.Name == "ASD")
.Select(p1 => p1.Outer))'
but I am getting back "could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information."
What I am doing wrong? I think problem is with ".Where(p1 => p1.Inner.Name == "ASD")"
Thank you for any ideas
Related
I have a linq query:
from cc in _db.CC
from pn in _db.AlertDbEntities
.Where(x => x.CompanyId == cc.Id)
.DefaultIfEmpty()
.Take(1)
join ns in _db.NS
on cc.Id equals ns.CompanyId
...
'Take()' part of which is translated into the following SQL code:
ROW_NUMBER() OVER (PARTITION BY ...)
The problem is that this function appeared only in Mysql 8.0, and the server for which I am writing has a version of Mysql 5.7. A lot of workarounds of this problem either cannot be transferred to SQL
The LINQ expression 'ProjectionBindingExpression: 1' could not be
translated. Either rewrite the query in a form that can be translated,
or switch to client evaluation explicitly by inserting a call to
'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'
Maybe you had a similar problem? How can it be solved?
I tried also this code:
from cc in _db.CC
from pn in _db.AlertDbEntities
.Where(x => x.CompanyId == cc.Id)
.OrderByDescending(n => n.CreatedAt)
.AsEnumerable()
.DefaultIfEmpty()
.Take(1)
.AsQueryable()
join ns in _db.NS
on cc.Id equals ns.CompanyId
...
//------------------------------------------
from cc in _db.СС
from pn in _db.AlertDbEntities
.Where(x => x.CompanyId == cc.Id)
.AsEnumerable()
.DefaultIfEmpty()
.OrderByDescending(n => n.CreatedAt)
.GroupBy(n => n.CompanyId)
.Select(g => g.FirstOrDefault())
join ns in _db.NS
on cc.Id equals ns.CompanyId
...
After migrating to .NET 6 I am receiving following errors.
var subsQuery = context.SubscriptionUsers
.Where(x => subscritpionIds.Contains(x.SubscriptionId));
var subscriptionUsers = await context.Users
.Include(x => x.UserSettings)
.Join(subsQuery, u => u.Id, su => su.UserId, (u, su) => new { su.SubscriptionId, User = u })
.GroupBy(x => x.SubscriptionId)
.ToDictionaryAsync(x => x.Key, x => x.Select(x => x.User).ToList());
This code throws:
The LINQ expression ... could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
I can't understand why it throws error, but hiding "GroupBy" part - solves it. My solution is this:
var subscriptionUsers = (await context.Users
.Include(x => x.UserSettings)
.Join(subsQuery, u => u.Id, su => su.UserId, (u, su) => new { su.SubscriptionId, User = u })
.ToListAsync())
.GroupBy(x => x.SubscriptionId)
.ToDictionary(x => x.Key, x => x.Select(x => x.User).ToList());
And I have another place, where I get same but different error:
var subscriptionsToSendTo = await context.Subscriptions
.Join(context.PricingPlans.Where(x => x.SystemName == "PromoOneUsd"), sub => sub.PricingPlanId, pp => pp.Id, (sub, pp) => sub)
.Include(x => x.SubscriptionUsers)
.ThenInclude(x => x.User)
.ThenInclude(x => x.UserSettings)
.Where(x =>
(x.EndDate < daysRangeFromNow && x.EndDate > DateTime.UtcNow) &&
(x.SubscriptionUsers.FirstOrDefault()
.User.UserSettings.FirstOrDefault(us =>
us.Name.Equals("ReceivedSevenDaysBeforeNinetyNineCentOfferExpires")
&& us.Value.Equals("true", StringComparison.InvariantCultureIgnoreCase)) == null
)
).ToListAsync();
Which throws:
The LINQ expression ... could not be translated. Additional information: Translation of the 'string.Equals' overload with a 'StringComparison' parameter is not supported. See https://go.microsoft.com/fwlink/?linkid=2129535 for more information. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
I fixed this with:
var subscriptionsToSendTo = await context.Subscriptions
.Join(context.PricingPlans.Where(x => x.SystemName == "PromoOneUsd"), sub => sub.PricingPlanId, pp => pp.Id, (sub, pp) => sub)
.Include(x => x.SubscriptionUsers)
.ThenInclude(x => x.User)
.ThenInclude(x => x.UserSettings)
.Where(x =>
(x.EndDate < daysRangeFromNow && x.EndDate > DateTime.UtcNow) &&
(x.SubscriptionUsers.FirstOrDefault()
.User.UserSettings.FirstOrDefault(us =>
us.Name.ToLower() == "receivedsevendaysbeforeninetyninecentofferexpires"
&& us.Value.ToLower() == "true") == null
)
).ToListAsync();
So I have questions:
Why first part throws exception?
Are my solutions alright? Any better solutions?
Regards
I have C# application (.NET Core 6) and I have written the following LINQ expression.
var data = query.OrderByDescending(a => a.CreatedOn).GroupBy(b => new { b.PackageID, b.PatientId }).ToList();
I get following error
The LINQ expression 'DbSet<LAB_ValueBasedResult>()
.Where(item => item.GroupId == 58)
.Where(item => item.HospitalId == 59)
.Where(x => x.IsActive)
.Where(x => x.CreatedOn >= __AddDays_0)
.Where(x => x.CreatedOn <= __AddDays_1)
.Where(x => __lstPatientID_2.Contains(x.PatientId))
.OrderByDescending(a => a.CreatedOn)
.GroupBy(b => new {
PackageID = b.PackageID,
PatientId = b.PatientId
})' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'.
I want to Add OrderByDescending and GroupBy in LINQ execute. how could I do it?
Please advise how can I resolve this.
Thank you.
Suppose I have a product in my database with the description “white shirt size 50”.
The search parameter would be “shirt 50”. I have a more complex query in which I add several “OR”s and I can't get them to work.
I get the following error:
The LINQ expression
'DbSet()
.Where(p => p.IdTienda == __request_IdTienda_0)
.Join(
inner: DbSet(),
outerKeySelector: p => p.IdArticulo,
innerKeySelector: a => a.Id,
resultSelector: (p, a) => new TransparentIdentifier<Publicacion, Articulo>(
Outer = p,
Inner = a
))
.Where(ti => __arrayrequest_1
.Any(s => ti.Outer.Descripcion.Contains(s)) || ti.Outer.Codigo == __request_Filtro_SearchText_2 || ti.Inner.Codigo == __request_Filtro_SearchText_2 || ti.Inner.CodigoUniversal == __request_Filtro_SearchText_2 || ti.Inner.CodigoUniversalBulto == __request_Filtro_SearchText_2)'
could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
My code so far is the following:
var arrayrequest = request.Filtro.SearchText.Split().ToList();
var query = from publicacion in _dbContext.Publicaciones.Where(p => p.IdTienda == request.IdTienda)
join articulo in _dbContext.Articulos
on publicacion.IdArticulo equals articulo.Id
where
arrayrequest.Any(s => publicacion.Descripcion.Contains(s))
|| publicacion.Codigo == request.Filtro.SearchText
|| articulo.Codigo == request.Filtro.SearchText
|| articulo.CodigoUniversal == request.Filtro.SearchText
|| articulo.CodigoUniversalBulto == request.Filtro.SearchText
select publicacion;
var publicaciones = await query
.Include(p => p.Articulo)
.Include(p => p.TributoPublicacion)
.ToArrayAsync();
The error occurs in the section
arrayrequest.Any(s => publicacion.Descripcion.Contains(s))`
I use Entity Framework Core 5 - any help is welcome
Don't want to repeat myself, but it is good to show how it can be solved.
EF do not supports complex predicates with local collections and here you need to build expression tree dynamically. This answer has GetItemsPredicate function which helps in building needed condition.
Then you can rewrite your query in this way:
var arrayrequest = request.Filtro.SearchText.Split().ToList();
var query = from publicacion in _dbContext.Publicaciones.Where(p => p.IdTienda == request.IdTienda)
join articulo in _dbContext.Articulos
on publicacion.IdArticulo equals articulo.Id
select publicacion;
var descriptionPredicate = query.GetItemsPredicate(arrayrequest, (publicacion, s) => publicacion.Descripcion.Contains(s));
Expression<Func<Publicacion, bool>> otherPredicate = publicacion => publicacion.Codigo == request.Filtro.SearchText
|| articulo.Codigo == request.Filtro.SearchText
|| articulo.CodigoUniversal == request.Filtro.SearchText
|| articulo.CodigoUniversalBulto == request.Filtro.SearchText;
query = query.Where(descriptionPredicate.CombineOr(otherPredicate)));
var publicaciones = await query
.Include(p => p.Articulo)
.Include(p => p.TributoPublicacion)
.ToArrayAsync();
List<string> groupId = request.GroupId.Split(',').ToList();
ENTITIES.ProductGroup
.Where(p => p.IsDisplay)
.Where(p => p.FK_GroupNavigation.IsDisplay)
.Where(p => groupId.Any(g => g == (p.FK_Group ?? 0) + "")
.ToList();
The value in request.GroupId is "12,15" and the same values are in the table, but give the following error.
In Ef Core I want to search for some value in another list but it gives the following error What is the problem?
TargetFramework=5.0
The LINQ expression 'DbSet()
.Where(p => p.IsDisplay)
.LeftJoin(
inner: DbSet(),
outerKeySelector: p => EF.Property<Nullable>(p, "FK_Group"),
innerKeySelector: g => EF.Property<Nullable>(g, "PK_Group"),
resultSelector: (o, i) => new TransparentIdentifier<ProductGroup, Group>(
Outer = o,
Inner = i
))
.Where(p => p.Inner.IsDisplay)
.Count(p => __groupId_0
.Any(g => (g ?? "").Equals((object)(p.Outer.FK_Group ?? 0) + "")))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'.
Any with local collection is not translatable to SQL, use Contains instead. Also compare integers by integer values, query will use indexes if they are exists.
List<int> groupId = request.GroupId.Split(',').Slect(s => int.Parse(s)).ToList();
SGP_PRODUCT.ProductGroup
.Where(p => p.IsDisplay)
.Where(p => p.FK_GroupNavigation.IsDisplay)
.Where(p => groupId.Contains(p.FK_Group))
.ToList();