Linq to Sql get today date only data from db - c#

i am unable to get the data from db with date only comparison. In Db InDateTime datatype is DateTime
using (HatronEntities context = new HatronEntities())
{
DateTime date = DateTime.Now.Date;
var AttendData = (from c in context.tbl_CoachMobAttendDetails
where c.CoachId == model.Id && c.InDateTime.Value.Date ==date
select c).FirstOrDefault();
}

using (HatronEntities context = new HatronEntities())
{
DateTime date = DateTime.Today;
DateTime until = date.AddDays(1);
var AttendData = (from c in context.tbl_CoachMobAttendDetails
where c.CoachId == model.Id &&
c.InDateTime.Value >= date &&
c.InDateTime.Value < until
select c).FirstOrDefault();
}
You didn't say initially that it was Linq To Entity Framework - but you say Linq To SQL! Then:
using (HatronEntities context = new HatronEntities())
{
DateTime date = DateTime.Today;
var AttendData = (from c in context.tbl_CoachMobAttendDetails
where c.CoachId == model.Id &&
DbFunctions.TruncateTime( c.InDateTime ) == date
select c).FirstOrDefault();
}

You can try like this:
c.InDateTime.Year == date.Year && c.InDateTime.Month == date.Month
&& c.InDateTime.Day == date.Day
or like
DbFunctions.TruncateTime(c.InDateTime.Value.Date) == date.Date

You can use DbFunctions.TruncateTime method:
DbFunctions.TruncateTime(c.InDateTime.Value.Date) == date.Date

Try Like this
c.InDateTime.Value.Date.Year == date.Year &&
c.InDateTime.Value.Date.Month == date.Month &&
c.InDateTime.Value.Date.Day == date.Day

Related

How to filter only when date is not null using optional condition

I am a little confused about how I can use the date as an optional condition.
if there is a date then <= of date, if the date is null then don't filter based on date.
My code is like this
DateTime date= DateTime.UtcNow.AddDays(-10);
foreach (var camEvent in dbContext
.CAM_EVENTS
.Where(c => c.USER_ID == userID &&
c.CAM_ID == cam.CAM_ID &&
c.EVENT_DATE >= date) // I want to change this like
.OrderByDescending(c => c.DATE))
{...}
I want that line to look something like this
(date && c.EVENT_DATE >= date)
so it only filter when date is not null, but this is not working.
I'd do the following logic:
(date==null || (c.EVENT_DATE >= date))
You can do something like this:
DateTime date = DateTime.UtcNow.AddDays(-10);
var filteredContext = dbContext
.CAM_EVENTS
.Where(c => c.USER_ID == userID &&
c.CAM_ID == cam.CAM_ID)
.OrderByDescending(c => c.DATE);
if (date != null) {
filteredContext = filteredContext.Where(c.EVENT_DATE >= date);
}
foreach (var camEvent in filteredContext) {
...
}
You can use a ternary operator, also known as a conditional operator.
foreach (var camEvent in dbContext
.CAM_EVENTS
.Where(c => c.USER_ID == userID &&
c.CAM_ID == cam.CAM_ID &&
// if date is not null, it will return bool c.EVENT_DATE >= date, otherwise just true
(date != null ? c.EVENT_DATE >= date : true))
.OrderByDescending(c => c.DATE))

Having problems forming a linq subquery in my Application Context

Here is an example of the SQL I am trying to convert to Linq
SELECT
* FROM assetassignment
WHERE asgn_type = 'trc' AND asgn_id = '54490' AND lgh_number <> 3015097 AND mov_number <>2030782
and asgn_enddate in (select max(asgn_enddate) FROM assetassignment
WHERE asgn_type = 'trc' AND asgn_id = '54490' AND lgh_number <> 3015097 AND mov_number <> 2030782 and asgn_enddate <= '03/19/2017')
I need to convert this to Linq. I am using a repository as follows:
public async task<AssetAssignment> FindPreviousTrip(string tractorNumber, DateTime endDate, int legNumber,string moveNumber)
{
using (var ctx = new AssetAssignmentContext(_nameOrConnectionString))
{
var previousTrip = from a in ctx.Set<AssetAssignment>()
where a.AssignmentType == "TRC" &&
a.AssignmentId == tractorNumber &&
a.LegId == legNumber &&
a.MoveNumber == moveNumber &&
a.EndDate).in()
}
}
As you can see I am making a stab at it, but keep failing on the subquery for the EndDate in statement.
I'll keep plugging at it, but any help is appreciated.
var previousTrip = from a in ctx.Set<AssetAssignment>()
where a.AssignmentType == "TRC" &&
a.AssignmentId == tractorNumber &&
a.LegId != legNumber &&
a.MoveNumber != moveNumber &&
a.EndDate == (from b in ctx.Set<AssetAssignment>()
where b.AssignmentType == "TRC" && b.AssignmentId == tractorNumber && b.LegId != legNumber && b.MoveNumber != moveNumber && b.EndDate <= new DateTime(2017, 19, 3)
select b.EndDate).Max()
select a;
You may want to create a variable for the common query
var baseTrip = from a in ctx.Set<AssetAssignment>()
where a.AssignmentType == "TRC" &&
a.AssignmentId == tractorNumber &&
a.LegId != legNumber &&
a.MoveNumber != moveNumber
select a;
var previousTrip = from a in baseTrip
where a.EndDate == (from b in baseTrip where b.EndDate <= new DateTime(2017, 19, 3) select b.EndDate).Max()
select a;

LINQ DateTime Query that ignores milliseconds

x.CreateDate DateTime is stored in our database down to milliseconds. My dateTimePicker values startdate and enddate only allows for querying down to seconds.
How can change my query to ignore the milliseconds of x.CreateDate? I thought the code I wrote below would work but it is not.
if (stardDateIsValid && endDateIsValid && startdate == enddate)
query = _context.Logs
.Where(x => x.ApplicationID == applicationId &&
x.CreateDate.AddMilliseconds(-x.CreateDate.Millisecond) == startdate)
.OrderByDescending(x => x.ID)
.Take(count);
var query = from l in _context.Logs
where l.ApplicationID == applicationId
&& SqlMethods.DateDiffSecond(l.CreateDate,startdate) == 0
orderby l.ID descending
select l).Take(count);
This avoids converting every date in you table into a string and the subsequent string comparison, by comparing the two dates as dates.
Getting CreateDate and startdate in the same format will help you compare apples to apples. This should accomplish that.
if (stardDateIsValid && endDateIsValid && startdate == enddate)
query = _context.Logs
.Where(x => x.ApplicationID == applicationId &&
x.CreateDate.ToString(#"MM/DD/YYYY h:mm:ss") == startdate.ToString(#"MM/DD/YYYY h:mm:ss")
.OrderByDescending(x => x.ID)
.Take(count);
I have no idea why I could not get any results from the queries posted above as I tried several variations of their themes. However I did get it working correctly by adding milliseconds to the startdate and enddate variables and it s working.
if (stardDateIsValid && endDateIsValid)
startdate = startdate.AddMilliseconds(000);
enddate = enddate.AddMilliseconds(999);
query = _context.Logs.Where(x => x.ApplicationID == applicationId && x.CreateDate >= startdate && x.CreateDate <= enddate).OrderByDescending(x => x.ID).Take(count);
You can create extension method.
public const long TicksPerMillisecond = 10000;
public const long TicksPerSecond = TicksPerMillisecond * 1000;
public static bool IsEqualIgnoreMilliseconds(this DateTime date, DateTime compareDate)
{
long tickDiff = date.Ticks - compareDate.Ticks;
return tickDiff > 0 ? tickDiff < TicksPerSecond : tickDiff < -TicksPerSecond;
}
Then you can use this:
if (stardDateIsValid && endDateIsValid && startdate == enddate)
query = _context.Logs
.Where(x => x.ApplicationID == applicationId &&
x.CreateDate.IsEqualIgnoreMilliseconds(startdate)
.OrderByDescending(x => x.ID)
.Take(count);

how to pass optional parameter in linq where condition

I have a action in MVC controller
public ActionResult ExportExcel(string ReportType,DateTime? FromDate,DateTime? ToDate)
{
var query = UnitOfWork.RepoTestResAnalysis.GetAll();
var QueryData = query.Where(s => s.MSO == ms && (FromDate != null && (s.TEST_DATE.Value >= FromDate)) && (ToDate!=null && (s.TEST_DATE.Value<=ToDate))).ToList();
}
Now If FromDate and ToDate are null then I am getting QueryData Count is Zero. But I need all records. So Can anyone tell me how can I get expected result. While FromDate & ToDate has value then I am getting expected result.
According to the information you have provided
Change you below statement:
var QueryData = query.Where(s => s.MSO == ms && (FromDate != null && (s.TEST_DATE.Value >= FromDate)) && (ToDate!=null && (s.TEST_DATE.Value<=ToDate))).ToList();
To
var QueryData = query.Where(s => s.MSO == ms && (FromDate == null || (s.TEST_DATE.Value >= FromDate)) && (ToDate == null || (s.TEST_DATE.Value<=ToDate))).ToList();
If the FromDate Or ToDate will be equal to NULL, it won't check them against s.TEST_DATE.Value.
You can do it like below also:
Change QueryData assignment to:
var QueryData = query.Where(s => s.MSO == ms &&
(s.TEST_DATE.Value >= (FromDate ?? DateTime.MinValue)) &&
(s.TEST_DATE.Value <= (ToDate ?? DateTime.MaxValue))).ToList();
I know it's an old question, but I will be glad if my code can help anybody.
I think following implementation will be the short and easy to read:
public ActionResult SomeMethod(string ReportType, DateTime? FromDate, DateTime? ToDate)
{
var query = UnitOfWork.RepoTestResAnalysis.GetAll();
var QueryData = query.Where(x => x.DateField >= (FromDate ?? x.DateField) && x.DateField <= (ToDate ?? x.DateField).ToList();
}

If statements are conflicting with each other - how to recitfy

I have two if statements and they both are conflicting with each other.
By default I can do filter by Dates and a Drop Down list from this if Statement:
DateTime fromDate = DateTime.MinValue;
DateTime toDate = DateTime.MaxValue;
if (dateFilter.Contains('~'))
{
fromDate = dateFilter.Split('~')[0] == "" ? DateTime.MinValue : Convert.ToDateTime(dateFilter.Split('~')[0]);
toDate = dateFilter.Split('~')[1] == "" ? DateTime.MaxValue : Convert.ToDateTime(dateFilter.Split('~')[1]);
}
filteredTracks = DataRepository.GetTracks()
.Where(c => (trackFilter == "" || c.TrackName.ToLower().Contains(trackFilter.ToLower()))
&&
(fromDate == DateTime.MinValue || fromDate < c.Date)
&&
(toDate == DateTime.MaxValue || c.Date < toDate)
);
but cannot do normal filtering records using this if statement, if the above one is being used:
if (!string.IsNullOrEmpty(param.sSearch))
{
var isTrackSearchable = Convert.ToBoolean(Request["bSearchable_1"]);
filteredTracks = DataRepository.GetTracks()
.Where(c => isTrackSearchable && c.TrackName.ToLower().Contains(param.sSearch.ToLower()));
}
else
{
filteredTracks = allTracks;
}
is it possible to have both of these to work?
Any help would be a great help :)
In such cases you can reuse the same query, conditionally adding Where clauses. E.g. for the second if-statement you can do just:
filteredTracks = filteredTracks.Where(...
Where filteredTracks already contains a result of first if-statement.

Categories