Subquery in a Lambda Expression or LINQ - c#

How can you write this query using a lambda expression or LINQ:
SELECT *
FROM vehicles
WHERE (memo1 like '%CERTIFIED%' OR memo2 = 'CERTIFIED')
AND stockno IN (SELECT stockno FROM udealer2 where ACC='UCERT')
ORDER BY model, days DESC

Not knowing much about your model, here is a blind mechanical translation of your query:
vehicles.Where( v =>
(SqlMethods.Like(v.memo1, "%CERTIFIED%") || v.memo2 == "CERTIFIED") &&
udealer2.Any(d => d.ACC == "UCERT" && d.stockno == v.stockno)
).OrderBy(v => v.model)
.ThenByDescending(v => v.days)

where Dealers.Any(d => d.Account == "UCERT" && something.StockNo == d.StockNo)

Related

Find in Entity Framework multiple OR parameters

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

How to make LINQ query with Unions more efficient

I inherited the LINQ query below and I feel that the query can be refactored for efficiency. The query currently takes about 6-8 seconds of processing time to return one record to the user on the front-end of the application. LINQ is not my strong suite, so any help would be greatly appreciated.
The query should ultimately produce a distinct list of CA_TASK_VW objects that are tied to a list of distinct CA_OBJECT_ID's obtained from the CA_OBJECT, CA_PEOPLE, and CA_CONTRACTOR tables.
var data = (from a in _db.CA_TASK_VW
where a.TASK_TYPE == "INSPECTION" && a.TASK_AVAILABLE_FLAG == "Y" && a.TARGET_END_DATE == null
select a).AsQueryable();
data = data.Join(_db.CA_OBJECT.Where(o => o.ENTERED_BY == _userId),
o => o.CA_OBJECT_ID, p => p.CA_OBJECT_ID,
(t, p) => t)
.Union(data.Join(_db.CA_PEOPLE.Where(p => p.EMAIL == _email),
t => t.CA_OBJECT_ID, p => p.CA_OBJECT_ID,
(t, p) => t))
.Union(data.Join(_db.CA_CONTRACTOR.Where(c => c.CONTRACTOR.EMAIL == _email),
t => t.CA_OBJECT_ID, c => c.CA_OBJECT_ID,
(t, c) => t));
The code seems to be using Join/Union to execute basically a where predicate on the list of CA_TASK_VW, filtering it step by step to the final result, so what happens if you just specify the where condition directly?
var data = from a in _db.CA_TASK_VW
where a.TASK_TYPE == "INSPECTION" && a.TASK_AVAILABLE_FLAG == "Y" && a.TARGET_END_DATE == null
select a;
data = data.Where(t => _db.CA_OBJECT.Where(o => o.ENTERED_BY == _userId).Select(o => o.CA_OBJECT_ID).Contains(t.CA_OBJECT_ID) ||
_db.CA_PEOPLE.Where(p => p.EMAIL == _email).Select(p => p.CA_OBJECT_ID).Contains(t.CA_OBJECT_ID) ||
_db.CA_CONTRACTOR.Where(c => c.CONTRACTOR.EMAIL == _email).Select(c => c.CA_OBJECT_ID).Contains(t.CA_OBJECT_ID));
You could try using UNION ALL if you don`t really care about duplicates in your query results as it works much faster than UNION

Lambda convert to LINQ

I don't know anything about lambda, and I can't even read a complicated lambda expression. I have this lambda code below that I want to convert into LINQ, but I don't know how.
var train = db.sample1
.Join(db.sample2, a => a.CertificateId, b => b.CertificateId, (a, b) => new { a, b })
.Where(x => x.a.Year.Value.Year == year && x.a.TrainingTypeId.Value == trainingTypeId && x.a.IsApproved.Value && x.b.EndDate >= DateTime.Now)
.Select(z => z.a).Distinct();
What I have tried so far and got stuck on:
var train = (from c in db.sample1
join in ts sample2 where a.CertificateId equals b.CertificateId
......
Lambda LINQ is still a link expression. However, the statement should look something like this:
var train2 = (from c in db.sample1
join t in db.sample2
on c.CertificateId equals t.CertificateId
where c.Year.Value.Year == year && c.TrainingTypeId.Value == trainingTypeId
&& c.IsApproved.Value && t.EndDate >= DateTime.Now
select c).Distinct();

Linq query for distinct data from a table with where condition

I have an sql statement like this:
select distinct(agent_name)
from properties
where agent_name not in ('null','')
I want the linq query in C# page
Assuming you're comparing to the string value 'null' like your original query:
List<string> agentNames = db.Properties.Where(p=>p.AgentName != "null" &&
p.AgentName != "")
.Select(p => p.AgentName)
.Distinct()
.ToList();
If you're actually comparing to a null value just change it to:
List<string> agentNames = db.Properties.Where(p=>p.AgentName != null &&
p.AgentName != "")
.Select(p => p.AgentName)
.Distinct()
.ToList();
var result = context.Properties.Where(p => p.AgentName != null
&& p.AgentName != "")
.GroupBy(p => p.AgentName)
.Select(g => g.Key);
Try something like this
var result = (from dbo in database.Table
where dbo.agent_name!=null and dbo.agent_name !=''
select dbo.agent_name).Distinct();
or if you have a list already
var result = (list.Where(a => a.agent_name!=null && a.agent_name!='').Select(
a.agent_name)).Distinct();
You can use it like this
var forms = db.properties.
Where(a => a.agent_name == 'null' || a.agent_name == null).
Select(x => x.agent_name).
Distinct().
ToList();
Its equivalent SQL statement, which is designed by LINQ to SQL is
SELECT
[Distinct1].[agent_name] AS [agent_name]
FROM ( SELECT DISTINCT
[Extent1].[agent_name] AS [agent_name]
FROM [dbo].[properties] AS [Extent1]
WHERE [Extent1].[agent_name] = N'null' OR [Extent1].[agent_name] = N''
) AS [Distinct1]

Use Lambda Expressions in a Query (C#)

How can I write lambda expression to get all orders who has detail row(s) with descriptions = "PickMe" or "TakeMe"
Try:
context.Orders.Where(o => o.OrderDetails.Any(d => d.Description == "PickMe" || d.Description == "TakeMe"));

Categories

Resources