I have a query like so:
if (catId == null || catId == 0)
{
productVM = db.Products
.Include(x => x.Category)
.ToArray()
.Select(x => new ProductVM(x))
.ToList();
}
else
{
productVM = db.Products
.Include(x => x.Category)
.ToArray()
.Where(x => x.CategoryId == catId)
.Select(x => new ProductVM(x))
.ToList();
}
That works, but as you can see the only difference between the 2 queries is .Where(x => x.CategoryId == catId).
Is there a more elegant way to write this?
Entity Framework doesn't actually query the database until you materialise the data, for example with ToList() or iterating over the results. So you can build up your query as you go without hitting the database:
var query = db.Products.Include(x => x.Category);
if(catId != null && catId != 0)
{
//Add a where clause
query = query.Where(x => x.CategoryId == catId);
}
productVM = query
.ToList()
.Select(x => new ProductVM(x));
Note that I removed the ToArray call as that also materialises the data which means each subsequent method on the data is acting on the entire table from the database.
You could expand the Where statement to include the test for null or 0 on catId. This might not work if the field catId in the database is nullable or can have a value of 0.
productVM = db.Products
.Include(x => x.Category)
.Where(x => catId == null || catId == 0 || x.CategoryId == catId)
.Select(x => new ProductVM(x))
.ToList();
Also you should remove the ToArray() as it queries the entire Products table from the database then perform the filtering and projecting in memory on the client.
Another way.
var products = db.Products.Include(x => x.Category).ToArray()
if (catId == null || catId == 0)
{
productVM = products.Select(x => new ProductVM(x)).ToList();
}
else
{
productVM = products.Where(x => x.CategoryId == catId)
.Select(x => new ProductVM(x)).ToList();
}
Simply re-assign query:
var query = db.Products;
if (condition)
query = query.Where(criteria);
var list = query.ToList();
Related
When var items = q3.ToList(); executes from the code snippet below, it throws exception System.NotSupportedException. The aim is to get the list of items after the grouping.
Exception:
Unable to create a constant value of type 'AppDB.Stage.Rules'. Only primitive types or enumeration types are supported in this context.
var valuations = context.stage
.Where(q => q.stageID == stageID && !rules.ToList().Any(r => r.type1 == q.type1 || r.type2 == q.type2))
.GroupBy(q => q.stageKey)
.Select(g => g) ;
var q3 = valuations.Select(y => new StageType
{
TypeKey = y.Key,
TypeName= "UNKNOWN",
});
var items = q3.ToList(); //error here
Your database doesn't have any idea of what your in-memory rules actually is, and in-turn cant convert this statement to SQL
The simplest solution will be to leave it as an IQueryable and don't use ToList,
context.stage
.Where(q => q.stageID == stageID && !rules.Any(r => r.type1 == q.type1 || r.type2 == q.type2))
.GroupBy(q => q.stageKey)
.Select(g => g) ;
However, if it is already in memory, then you will have to send the values as a primitive list
var type1s = rules.Select(x => x.type1);
var type2s = rules.Select(x => x.type2);
context.stage
.Where(q => q.stageID == stageID && !type1s.Contains(q.type1) && !type2s.Contains(q.type2))
.GroupBy(q => q.stageKey)
.Select(g => g) ;
Because rules.ToList() makes results in memory, you can't use it inside an IQueryable that executes over SQL. You should first bring your data into memory and then narrow it by other in-memory object.
var valuations = context.stage.ToList()
.Where(q => q.stageID == stageID && !rules.ToList().Any(r => r.type1 == q.type1 || r.type2 == q.type2))
.GroupBy(q => q.stageKey)
.Select(g => g) ;
var q3 = valuations.Select(y => new StageType
{
TypeKey = y.Key,
TypeName= "UNKNOWN",
});
var items = q3.ToList();
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
...
Could you help me to improve this code?
var orderNo = "1234";
var maxValue = MyTable.Where(x => x.OrderNo == orderNo )
.OrderByDescending(x => x.Filename)
.Select(x => x.Filename)
.FirstOrDefault();
var list = (from x in MyTable
where x.OrderNo == orderNo && x.Filename == maxValue
select x).Distinct();
list.Dump();
Is it possible to improve these 2 Linq queries into 1 and avoiding query 2 times my database. Something like:
var list = (from x in MyTable
where x.OrderNo == orderNo && MaxValue(x.Filename)
select x)
.Distinct();
You could use GroupBy:
var list = MyTable
.Where(x => x.OrderNo == "1234") // or var1
.GroupBy(x => x.Filename)
.OrderByDescending(g => g.Key)
.First()
.Distinct();
Try
var list = (
from x in MyTable
where x.OrderNo == var1 &&
x.Filename == MyTable.Where(x => (x.OrderNo == "1234")).Max(p => p.Filename)
select x
).Distinct();
Why not just:
MyTable.Where(x => x.OrderNo == "1234")
.Max(x => x.Filename);
You will get all the records that have the maximal filename.
I use the query below to get all columns(20 more) in Entity Framework Linq. Because of out of memory exception, I only want to get two of them. One is "FileName", the other one is "FilePath". How to modify my code?
var query = DBContext.Table1
.Where(c => c.FacilityID == facilityID && c.FilePath != null && c.TimeStationOffHook < oldDate)
.OrderBy(c => c.FilePath)
.Skip(1000)
.Take(1000)
.ToList();
foreach(var t in query)
{
Console.WriteLine(t.FilePath +"\\"+t.FileName);
}
var query = DBContext.Table1.Where(c => c.FacilityID == facilityID && c.FilePath != null && c.TimeStationOffHook < oldDate)
.OrderBy(c => c.FilePath)
.Skip(1000)
.Take(1000)
.Select(c => new { c.FilePath, c.FileName })
.ToList();
foreach(var t in query)
{
Console.WriteLine(t.FilePath +"\\"+t.FileName);
}
You need to use Select.
Just select out two of the columns:
DBContext.Table1.Select(c => new { c.FileName, c.FilePath });
How about something like
using (var entity = new MyModel(ConnectionString))
{
var query = (from myTable in entity.theTable
where myTable.FacilityID == facilityID &&
myTable.FilePath != null &&
myTable.TimeStationOffHook < oldDate
orderby myTable.FilePath
select new
{
myTable,FileName,
myTable.FilePath
}).Skip(1000).Take(1000).ToList();
//do what you want with the query result here
}
I am trying to write a LINQ statement with some optional where clauses. This is for a search. The user can select a specific site to search or search against all sites:
var query =
_db.STEWARDSHIP
.OrderBy(r => r.SITE.SITE_NAME)
.Where(r => r.SITE_ID == SiteId)
.Where(r => r.VISIT_TYPE_VAL.VISIT_TYPE_ID == VisitTypeId)
.Select(r => new
{
id = r.STEWARDSHIP_ID,
name = r.SITE.SITE_NAME,
visit_type = r.VISIT_TYPE_VAL.VISIT_TYPE_DESC,
visit_date = r.VISIT_DATE
});
return query;
So when the method gets SiteId = 14, for instance, no problem. However, when it gets SiteId = null, then that where clause should not be considered.
Thanks
Eric
That's easy:
var query = _db.STEWARDSHIP.OrderBy(r => r.SITE.SITE_NAME);
if (SiteId != null)
{
query = query.Where(r => r.SITE_ID == SiteId);
}
query = query.Where(r => r.SITE.SITE_TYPE_VAL.SITE_TYPE_ID == SiteTypeId)
.Select(r => new
{
id = r.STEWARDSHIP_ID,
name = r.SITE.SITE_NAME,
visit_type = r.VISIT_TYPE_VAL.VISIT_TYPE_DESC,
visit_date = r.VISIT_DATE
});
return query;
This works because queries compose nicely - and they really only represent queries; it's only when you try to fetch data from them that the query is actually executed.
Can't you just edit the where clause to something like
.Where(r=>SiteId == null || r.SiteId == SiteId)
you can use where clause in one statement ..like this ..
.Where(r => SiteID == null || r.SITE_ID == SiteID)
I'm stealing a trick from TSQL. Just check for the null value as well.
...
.Where(r => SiteID == null || r.SITE_ID == SiteID)
...
The SQL example is this:
WHERE (SITE_ID = #given OR #given IS NULL) --return matches or all
Though if that value is mutable and you want the value at the time the query was built, try this instead:
var localSiteID = SiteID;
...
.Where(r => localSiteID == null || r.SITE_ID == SiteID)
...