I'm trying to use LINQ to get a list of values.
I have code like this:
var _context = _scope.ServiceProvider.GetRequiredService<VMContext>();
if (boolparameter)
{
var listCE = _context.Ce
.Where(x => x.VuId == element.VuId)
.Where(x => x.Score == 8)
.AsNoTracking()
.ToList();
}
else
{
var listCE = _context.Ce
.Where(x => x.VuId == element.VuId)
.AsNoTracking()
.ToList();
}
Depends on boolparameter, I do a query or another one. Is there a way to use a single query with a conditions inside?
Something like:
var listCE = _context.Ce
.Where(x => x.VuId == element.VuId)
.Where(x => boolparameter ? x.Score == 8 : true)
.AsNoTracking()
.ToList();
C# Asp.NetCore SqlServer 2019
Thanks a lot!
You could try the following code if it works:
var listCE = _context.Ce
.Where(x => x.VuId == element.VuId)
.Where(x => !boolparameter || x.Score == 8)
.AsNoTracking()
.ToList();
Which means if boolparameter is false, x.Score doesn't matter, since !false would equal to true and it satisfies OR condition. Likewise if boolparameter is true, then x.score will also be checked if it is equal to 8.
Or maybe with one Where condition:
var listCE = _context.Ce
.Where(x => x.VuId == element.VuId && (!boolparameter || x.Score == 8))
.AsNoTracking()
.ToList();
var listCE = _context.Ce
.Where(x =>
x.VuId == element.VuId
&& (!boolparameter || x.Score == 8))
.AsNoTracking()
.ToList();
This checks whether boolparameter is true before checking x.Score.
Can you check that below?
var listCE = _context.Ce
.Where(x => boolparameter == false ? x.VuId == element.VuId :
(x.VuId == element.VuId &&
x.Score == 8))
.AsNoTracking()
.ToList();
This way is more verbose, but if you have more (or complicated) conditions it can be easier to read and quickly understand what affects the query.
LINQ doesn't execute the query until you reach .ToList() or otherwise try to access the result from the query.
This means you don't need to have the full query duplicated in both the if and else part:
var _context = _scope.ServiceProvider.GetRequiredService<VMContext>();
var listCEQuery = _context.Ce.Where(x => x.VuId == element.VuId)
// LINQ will append this to the initial where clause
if (boolparameter == true)
listCEQuery = listCEQuery.Where(x => x.Score == 8)
var listCE = listCEQuery.AsNoTracking().ToList();
Related
i have this:
int item = particleEdges.ElementAt(i).Key;
Point3 hashPoint = particleEdges[item][j].hashEdge;
var hashList = particleEdges
.Where(p => p.Value.Any(q => q.hashEdge == hashPoint))
.Select(r => r.Key != item)
.ToList();
How to exclude "item" from hashList? Broke my head. Linq doesn't want to open to me.
var hashList = particleEdges
.Where(p => p.Value.Any(q => q.hashEdge == hashPoint))
.Where(r => r.Key != item)
.Select(s => s.Key)
.ToList();
Something like this:
Itens = db.Transacao.AsNoTracking()
if (x == 1)
.Where(w => w.Confirmado == true)
else
.Where(w => w.Data.Date >= DateTime.Now.Date)
.Include(i => i.Pessoa)
.Include(i => i.Categoria)
.ToList();
I know that this don't exist, but, exist something similar to this?
Well, you can do something like this:
IQueryable<[your entity here]> query = db.Transacao.AsNoTracking();
if (x == 1)
query = query.Where(w => w.Confirmado == true);
else
query = query.Where(w => w.Data.Date >= DateTime.Now.Date);
return query.Include(i => i.Pessoa)
.Include(i => i.Categoria)
.ToList();
Hope it helps.
I'm trying to return an IEnumerable activities instead of "var"
var activities = ctx.Activities.Where(a => a.SiteID == propID)
.Where(a => a.ActivityTypeName == "Call")
.Select(x => new
{
x.DateTimeEntry,
x.Contact.OwnerContact.ParcelDatas
.FirstOrDefault(a => a.OwnerContactID == x.Contact.OwnerContact.OOwnerID)
.Parcel_LetterTracking.LMailDate,
x.FAQs.FirstOrDefault(a => a.ActivityID == x.ActivityID)
.FAQ_Library.FaqNum,
x.FAQs.FirstOrDefault(a => a.ActivityID == x.ActivityID)
.FAQ_Library.Question
});
edit: data type Object compiles but I'm not sure if that's right.
.Select already returns a an IEnumerable<TResult> also combine your ..where() clauses with && instead. https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select?view=netframework-4.8 also one other thing you can do is use .AsEnuemerable()
var activities = ctx.Activities.Where(a => a.SiteID == propID && a.ActivityTypeName == "Call")
.Select(x => new
{
x.DateTimeEntry,
x.Contact.OwnerContact.ParcelDatas.FirstOrDefault(a => a.OwnerContactID == x.Contact.OwnerContact.OOwnerID).Parcel_LetterTracking.LMailDate,
x.FAQs.FirstOrDefault(a => a.ActivityID == x.ActivityID).FAQ_Library.FaqNum,
x.FAQs.FirstOrDefault(a => a.ActivityID == x.ActivityID).FAQ_Library.Question
}).AsEnumerable();
I getting this error when I join:
An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: The specified LINQ expression contains references to queries that are associated with different contexts.
var rightsList = RoleRightService.GetRoleRights<RoleRight>().Where(x => x.RoleCode == role && x.CompanyId == USER_OBJECT.CompanyId).AsEnumerable();
var securables = SecurableServices.GetSecurable<Securable>()
.GroupBy(a => new { a.RegistrationType_LookUpId })
.Select(r => new
{
id = r.Select(x => x.SecurableID),
registrationType = r.Key.RegistrationType_LookUpId,
RegistrationTypeName = r.Select(x => x.RegistrationType.LookUpDescription).Distinct().FirstOrDefault(),
IsChecked = false,
pageList = r.GroupBy(b => new { b.PageID })
.Select(p => new SecurableViewModel
{
Id = p.Where(x => x.PageID == p.Key.PageID && x.Type == 1).Select(x => x.SecurableID).FirstOrDefault(),
PageId = p.Where(x => x.PageID == p.Key.PageID && x.Type == 1).Select(x => x.PageID).FirstOrDefault(),
PageName = p.Where(x => x.PageID == p.Key.PageID && x.Type == 1).Select(x => x.PageDescription).FirstOrDefault(),// && rr.AccessRight !=0
IsChecked = rightsList.Where(rr => rr.SecurableID == (p.Where(x => x.PageID == p.Key.PageID && x.Type == 1).Select(x => x.SecurableID).FirstOrDefault())).Count() > 0,
operationList = r.Where(x => x.PageID == p.Key.PageID && x.Type == 2)
.Select(o => new RoleRightViewModel
{
Id = o.SecurableID,
OperationID = o.OperationID,
OperationName = o.OperationDescription,
IsChecked = rightsList.Where(rr => rr.SecurableID == o.SecurableID).Count() > 0,
})
.ToList()
}).ToList()
}).ToList();
I am getting error
The specified LINQ expression contains references to queries that are associated with different contexts.
For this line:
IsChecked = rightsList.Where(rr => rr.SecurableID == (p.Where(x => x.PageID == p.Key.PageID && x.Type == 1).Select(x => x.SecurableID).FirstOrDefault())).Count() > 0,
is there possibilty to right delegate for this
It looks like you are using multiple EF entity contexts, possibly to query more than one database. EF is not able to perform a linq to entities query across more than one EF context.
In order to execute this query without error is will be necessary to use linq to objects instead by projecting the data from each context into memory before combining them. Please note this may have a negative performance impact since all objects will need to be fetched into memory before being filtered down.
Try adding a .ToList() between your GroupBy and Select statements:
var securables = SecurableServices.GetSecurable<Securable>()
.GroupBy(a => new { a.RegistrationType_LookUpId })
.ToList()
.Select(r => new
...
Please see the code below:
var pcPageList = db.PcPages
.Where(m =>
m.Quarter == exactQuarter &&
m.Url == pageUrl &&
m.UpdatedOn.ToDateTime().Date.ToString("dd/MMM").ToLower() == "02/nov")
.OrderBy(m => m.UpdatedOn)
.FirstOrDefault();
When I run this above, the application throws error says: "ToDateTime" is not implemented yet. Anyone please can advice ?
How about:
var updateStart = DateTime.ParseExact("02/nov", "dd/MMM", CultureInfo.InvariantCulture);
var updateEnd = updateStart.AddDays(1.0);
var pcPageList = db.PcPages
.Where(m =>
m.Quarter == exactQuarter &&
m.Url == pageUrl &&
m.UpdatedOn >= updateStart &&
m.UpdatedOn < updateEnd)
.OrderBy(m => m.UpdatedOn)
.FirstOrDefault();
I think, you should be calling ToDateTime using Convert class as:
Convert.ToDateTime(m.UpdatedOn).Date...
And remove the Date in between as:
Convert.ToDateTime(m.UpdatedOn).ToString("dd/MMM").ToLower() == "02/nov"
Rather than doing a string comparison, it would be more efficient to compare the date components directly. I haven't tested this, but something like the following may work:
var pcPageList = db.PcPages
.Where(m => m.Quarter == exactQuarter && m.Url == pageUrl)
// You may need to materialize the results of the query at this point
// or use Convert.ToDateTime(...) instead of ToDateTime()
.Select(m => new { Row = m, UpdatedOn = m.UpdatedOn.ToDateTime() })
.Where(a => a.UpdatedOn.Month == 11 && a.UpdatedOn.Day == 2)
.Select(a => a.Row)
.OrderBy(m => m.UpdatedOn)
.FirstOrDefault();