Optional compare in query - entity-framework

Hi i have a problem with my query because i want select that items which brands are called in string subcategory. But if that subcategory is equal "none" i would to select them all i want to do it in query not in linq. Here's my function
string subcategory = HttpContext.Current.Session["subcategory"].ToString() == "none" ? "" : HttpContext.Current.Session["subcategory"].ToString();
List<int> processors = (from x in context.Processors
where (x.Price >= filters.PriceMin && x.Price <= filters.PriceMax)
where x.Brand == subcategory
select x.Product_ID).ToList();

The pattern for this in LINQ and EF is to build up the query differently for the two cases before the query is executed by calling IQueryable.ToList(); eg:
string subcategory = ...;
var q = from x in context.Processors
where (x.Price >= filters.PriceMin && x.Price <= filters.PriceMax)
select x;
if (subcategory != "none")
{
q=q.Where(x => x.Brand == subcategory);
}
var processors = q.Select(x => x.Product_ID).ToList();

Related

How to do aggregate functions such as count in Entity Framework Core

I have this SQL that I would like to execute in Entity Framework Core 2.1:
Select ItemTypeId, Count(ItemTypeId) as Count from Items i
where i.ParentId = 2
group by ItemTypeId
How do I do that?
This is what I came up with, but it returns zero:
var query = this._context.Items.Where(a => a.ParentId == 2)
.GroupBy(i => new { i.ItemTypeId })
.Select(g => new { g.Key.ItemTypeId, Count = g.Count(i=> i.ItemTypeId == g.Key.ItemTypeId) });
var items = query.ToList();
The only example I could find was here
You don't need Count = g.Count(i=> i.ItemTypeId == g.Key.ItemTypeId), instead use g.Count().

Linq query on a Date giving an error "Nullable object must have a value."

I have a list of objects that I'm passing into a function where I want to filter out records for a specific company and if a DateTime field is today.
I'm getting an error "Nullable object must have a value." when I do and I believe it is due to the fact that some of the "Verified_Date" fields are null, but not all of them.
This is the LINQ I came up with. Is there a way that I can filter out on a specific company and if there Verified_Date = today even if some of the records have a Verified_Date = NULL?
var today = DateTime.Today;
var listFiltered = data.Where(d => d.CompanyCode == companyCode && d.VerifiedDate.Value.Date == today).ToList();
You can try this:
var today = DateTime.Today;
var listFiltered = data.Where(d => d.CompanyCode == companyCode
&& d.VerifiedDate!=null
&& d.VerifiedDate.Value.Date == today).ToList();
Check that VerifiedDate isn't null in your Where condition.
var listFiltered = data.Where(d => d.CompanyCode == companyCode
&& d.VerifiedDate != null
&& d.VerifiedDate.Value.Date == DateTime.Today)
.ToList();

Linq to entities where condition not working

var records = (from m in ctx.myData
from StatusReport in ctx.ReportStatusDetails
where (m.UserId == user.UserId &&
StatusReport.StatusId == 1 &&
ctx.Report.Any(r => r.ReportDate.Month == SqlFunctions.GetDate().Value.Month &&
r.ReportDate.Year == SqlFunctions.GetDate().Value.Year))
select new
{
m.Id,
m.Company.CompanyName,
m.UserId,
m.aspnet_Membership.aspnet_Users.UserName,
m.aspnet_Membership.Email
})
.Distinct()
.ToList();
The where condition StatusReport.StatusId == 1 is not working. The query is returning even rows where StatusReport.StatusId is not equal to 1.
Why is this condition being ignored?
Because you did not joined/related StatusReport with m. And result contains only m. See example http://msdn.microsoft.com/en-us/library/bb311040.aspx

Excluding child records from entity objects c#

I am having an issue with writing a query to exclude records from entity framework child objects.
My query
var response = db.USER_PROFILE.Where(x =>
x.IPAD_SERIAL_NUMBER == id
&& x.ACTIVE_FLAG == 1
&& x.USER_BRAND.Any(y => y.ACTIVE_FLAG == 1)
).FirstOrDefault();
Returned result
One USER_PROFILE object with
Two USER_BRAND objects
USER_BRAND - ACTIVE_FLAG = 1
USER_BRAND - ACTIVE_FLAG = 0
I don't want to return a record with ACTIVE_FLAG = 0 in the collection.
How do I do easily that?
Thanks in advance!
I was able to do it this way
var query = db.USER_PROFILE
.Select(x=> new
{
User = x,
UserBrands = x.USER_BRAND.Where(y=> y.ACTIVE_FLAG == 1)
.Select(a=> new
{
UserBrand = a,
Brand = a.BRAND
}),
});
var filtered = query.Select(x=> x.User);

Entity Framework - Select * from Entities where Id = (select max(Id) from Entities)

I have an entity set called Entities which has a field Name and a field Version. I wish to return the object having the highest version for the selected Name.
SQL wise I'd go
Select *
from table
where name = 'name' and version = (select max(version)
from table
where name = 'name')
Or something similar. Not sure how to achieve that with EF. I'm trying to use CreateQuery<> with a textual representation of the query if that helps.
Thanks
EDIT:
Here's a working version using two queries. Not what I want, seems very inefficient.
var container = new TheModelContainer();
var query = container.CreateQuery<SimpleEntity>(
"SELECT VALUE i FROM SimpleEntities AS i WHERE i.Name = 'Test' ORDER BY i.Version desc");
var entity = query.Execute(MergeOption.OverwriteChanges).FirstOrDefault();
query =
container.CreateQuery<SimpleEntity>(
"SELECT VALUE i FROM SimpleEntities AS i WHERE i.Name = 'Test' AND i.Version =" + entity.Version);
var entity2 = query.Execute(MergeOption.OverwriteChanges);
Console.WriteLine(entity2.GetType().ToString());
Can you try something like this?
using(var container = new TheModelContainer())
{
string maxEntityName = container.Entities.Max(e => e.Name);
Entity maxEntity = container.Entities
.Where(e => e.Name == maxEntityName)
.FirstOrDefault();
}
That would select the maximum value for Name from the Entities set first, and then grab the entity from the entity set that matches that name.
I think from a simplicity point of view, this should be same result but faster as does not require two round trips through EF to sql server, you always want to execute query as few times as possible for latency, as the Id field is primary key and indexed, should be performant
using(var db = new DataContext())
{
var maxEntity = db.Entities.OrderByDecending(x=>x.Id).FirstOrDefault()
}
Should be equivalent of sql query
SELECT TOP 1 * FROM Entities Order By id desc
so to include search term
string predicate = "name";
using(var db = new DataContext())
{
var maxEntity = db.Entities
.Where(x=>x.Name == predicate)
.OrderByDecending(x=>x.Id)
.FirstOrDefault()
}
I think something like this..?
var maxVersion = (from t in table
where t.name == "name"
orderby t.version descending
select t.version).FirstOrDefault();
var star = from t in table
where t.name == "name" &&
t.version == maxVersion
select t;
Or, as one statement:
var star = from t in table
let maxVersion = (
from v in table
where v.name == "name"
orderby v.version descending
select v.version).FirstOrDefault()
where t.name == "name" && t.version == maxVersion
select t;
this is the easiest way to get max
using (MyDBEntities db = new MyDBEntities())
{
var maxReservationID = _db .LD_Customer.Select(r => r.CustomerID).Max();
}