Date comparision - linq

In LINQ, I write a query for data, which is between two dates. In this case I am not getting data. When user enters same date as from date and to date the data is not displaying while there are data for that particular date.
This is my LINQ query.
var result = from MaterialStatus in materialRequistionEntities.Tbl_MatReq_NewItemReq_M
join CurrentStatus in materialRequistionEntities.Tbl_StatusMaster_M
on MaterialStatus.ReqCurStatus equals CurrentStatus.StatusId
join Employee in materialRequistionEntities.Tbl_Emp_Master_M
on MaterialStatus.Indentor equals Employee.EmpId
where (MaterialStatus.CreatedOn >= dt.Date
&& MaterialStatus.CreatedOn <= dt1.Date)
select *****************

You should do:
var upperDate = dt1.Date.AddDays(1);
...
where (MaterialStatus.CreatedOn >= dt.Date
&& MaterialStatus.CreatedOn < upperDate
This way the expression can be converted to a sargable SQL predicate.

Assuming that dt1 is in reality greater that dt, you could use
var result = from MaterialStatus in materialRequistionEntities.Tbl_MatReq_NewItemReq_M
join CurrentStatus in materialRequistionEntities.Tbl_StatusMaster_M on
MaterialStatus.ReqCurStatus equals CurrentStatus.StatusId
join Employee in materialRequistionEntities.Tbl_Emp_Master_M
on MaterialStatus.Indentor equals Employee.EmpId
where (MaterialStatus.CreatedOn.Date >= dt.Date && MaterialStatus.CreatedOn.Date <= dt1.Date)
select *****************
Notice CreatedOn.Date to deal with the hour/minute/seconds/milliseconds components

I hope it will be ok.
where (MaterialStatus.CreatedOn.Value.Date >= dt.Date && MaterialStatus.CreatedOn.Value.Date <= dt1.Date.AddDay(1))

Related

BETWEEN operator for string in LINQ to SQL query

from p in table
where ID == 201
&& date => 20160601
&& date <= 20160901
select {ID, name};
q.Dump();
The date in the database is in string simple format.
I am trying to convert a SQL query to LINQ. In SQL, BETWEEN operator is being used to select values within a given range. But, BETWEEN can't be used with LINQ statement, so I am getting an error which says => cannot be applied to operands of type string and int for the date field. Any help would be appropriated. I tried the DateTime, but it didn't work for me.
Since LINQ to Entities doesn't support Convert.ToDateTime (why not?) and your date formats are in a reasonable string format, you can compare as strings:
from p in table
where ID == 201
&& date.CompareTo("20160601") >= 0
&& date.CompareTo("20160901") <= 0
select { ID, name };
Try this working code:
var q = from p in table
where p.ID == 201
&& p.date >= DateTime.ParseExact("20160601", "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture)
&& p.date <= DateTime.ParseExact("20160901", "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture)
select p;
q.Dump();

Linq how to join tables with a where clause on each table and a count

The following LINQ query isn't allowed when I use multiple where elements - it stops liking the 'into':
var query =
from ph in _db.PlayHits
join ua in _db.UserAgents on ph.UserAgentId equals ua.UserAgentId
where (ph.VideoId == 1 && ua.AgentString.Contains("test"))
into hits
select new
{
ResultCount = hits.Count()
};
Any idea why or how I amend this?
The equivilent sql I want is:
select count(*) as ResultCount
from Playhits ph
join UserAgents ua on ph.UserAgentId = ua.UserAgentId
where ph.VideoId = 1
and ua.AgentString like '%test%'
To my understanding, counting of the results can be done using the extension methond Count as follows.
var query =
from ph in _db.PlayHits
join ua in _db.UserAgents on ph.UserAgentId equals ua.UserAgentId
where (ph.VideoId == 1 && ua.AgentString.Contains("test"));
int Result = query.Count();

linq join with less than or equal to int value

I wanting to know the best approach for a where clause with less than or equal to where the value to match is int?
var outOfStockProducts = (from theMapProd in context.tblProductOptions_MAP
join theProd in context.tblProducts on theMapProd.productID equals theProd.productID
where theProd.stock_Level <= 5
select theMapProd).ToList();
This is another way,
Not tested.
var outOfStockProducts = (from theMapProd in context.tblProductOptions_MAP
join theProd in context.tblProducts on theMapProd.productID equals theProd.productID
select theMapProd).ToList();
outOfStockProducts=outOfStockProducts.where(x=>x.stock_Level < 5 || x.stock_Level ==5).ToList();

Combining two tables using linq

i have two linq - sql queries, and im wondering how to join them..
First Query
var ab = from a in Items_worker.getCEAItems()
where a.ProjectCode == lbl_projectCode.Text
select new
{
a.ID
};
Second Query
var j = from c in tblInc_worker.get(c => c.MarginID == MarginID && c.IncTypeID == "CAPEX")
orderby c.DateCreated
select c.ID;
First Query would return:
fasf-1212-1212-1212-1212
afaa-1414-1414-1414-1414
Second Query would return:
fasf-1212-1212-1212-1212
afaa-1414-1414-1414-1414
0000-0000-0000-0000-0000
1111-1111-1111-1111-1111
question is how can i possibly join the two table. Wherein the second query should return all of the records with the same ID found in the first query plus the id containing "0000-0000-0000-0000-0000" second query..
The result should be:
fasf-1212-1212-1212-1212
afaa-1414-1414-1414-1414
0000-0000-0000-0000-0000
You can use union to join the both queries, for example split your second query in two with conditions like :
var ab = from a in Items_worker.getCEAItems()
where a.ProjectCode == lbl_projectCode.Text
select new
{
a.ID
};
var j = from c in tblInc_worker.get(c => c.MarginID == MarginID && c.IncTypeID == "CAPEX")
orderby c.DateCreated
select c.ID where c.ID.Equals("0000-0000-0000-0000-0000");
var j1 = from c in tblInc_worker.get(c => c.MarginID == MarginID && c.IncTypeID == "CAPEX")
orderby c.DateCreated
select c.ID where !(c.ID.Equals("0000-0000-0000-0000-0000"));
var result = ab.Union(j.Union(j1));
Hope this helps..

orderby nested linq

var query = from m in db.Members.Include("Companies.Projects.Experiences.ExperienceTags")
where m.MemberId == id
select m;
I would like to also from this query to orderby the project.enddate. How would I do that. Also enddate can be null which then I would like it to be today date when it orderby. And, a company might not always have a project either which then it should be orderby today date too.
here is a image of the ef data diagram a link
Since there is a many relationship you need to do a SelectMany like so:
var query = from m in db.Members.Include("Companies.Projects.Experiences.ExperienceTags")
where m.MemberId == id
orderby m.Companies.SelectMany(c => c.Projects).OrderByDescending(p => p.EndDate).FirstOrDefault() == null ?
DateTime.Today :
m.Companies.SelectMany(c => c.Projects).OrderByDescending(p => p.EndDate).FirstOrDefault()
select m;

Resources