Linq date comparision - c#

My query is like
var TMJM = (from TT in r2ge.Transcription_Tracker
join TMA in r2ge.Transcription_Master on TT.Transcription_Id equals TMA.Transcription_Id
select new
{
Trans_Id = TMA.Transcription_Id,
Modified_dtm = TMA.Modified_dtm
}).Distinct();
var qq = TMJM.Where(dr => (dr.Modified_dtm.Date >= sev_back_datetime) && (dr.Modified_dtm.Date <= DateTime.Now.Date));
It gives output Enumeration yielded no results while Data is there
But when I separate start date and end date then It will show date but when I combine both start and end date then It won't give output..
Any mistake in query?

Evaluating each part of the date could be fraught with issue. I am assuming you are doing this to remove the time portion which can sometimes be problematic. Subsequently you can just evaluate the 'date' portion of the date time variable. This little example should explain.
class Program
{
static void Main(string[] args)
{
List<DateTime> dates = new List<DateTime>();
dates.Add(DateTime.Now.AddDays(-50));
dates.Add(DateTime.Now.AddDays(-51));
dates.Add(DateTime.Now.AddDays(-52));
dates.Add(DateTime.Now.AddDays(-53));
dates.Add(DateTime.Now.AddDays(-99));
dates.Add(DateTime.Now.AddDays(-100));
dates.Add(DateTime.Now.AddDays(-101));
var sev_back_datetime = DateTime.Now.AddDays(-100);
Console.WriteLine(sev_back_datetime.Date.ToShortDateString());
Console.WriteLine("---------------------");
var query = from date in dates
where date.Date >= sev_back_datetime.Date &&
date.Date <= DateTime.Now.Date
select date;
foreach (var date in query.ToList())
Console.WriteLine(date.ToShortDateString());
Console.ReadLine();
}
}
EDIT - a direct example for you.
var TMJM = (from TT in r2ge.Transcription_Tracker
join TMA in r2ge.Transcription_Master on TT.Transcription_Id equals TMA.Transcription_Id
select new
{
Trans_Id = TMA.Transcription_Id,
Modified_dtm = TMA.Modified_dtm
}).Distinct();
var qq = TMJM.Where(dr => (EntityFunctions.TruncateTime(dr.Modified_dtm) >= EntityFunctions.TruncateTime(sev_back_datetime)) && (EntityFunctions.TruncateTime(dr.Modified_dtm) <= EntityFunctions.TruncateTime(DateTime.Now)));

Related

C# EF: How to search between two dates in EF but want to exclude time from data

i do not know how to execlude time from data when doing comparison in EF.
using (var db = new DbContext())
{
var query = from n in db.BDatas
orderby n.AddDate,n.CountryCode
where n.CountryCode=="GB"
&& (n.AddDate >= stdate.Date && n.AddDate <= etdate)
select n;
}
i guess my above query will include date and time when comparision will occur. so tell me what to do?
You don't need to exclude time from SQL comparison. You can just exclude time from parameters which you are passing:
using (var db = new DbContext())
{
var startDate = stdate.Date;
var endDate = etDate.Date.AddDays(1);
var query = from n in db.BDatas
orderby n.AddDate,n.CountryCode
where n.CountryCode=="GB"
&& (n.AddDate >= startDate && n.AddDate < endDate)
select n;
}
Note that I used < endDate and added one more day to it. Thus you will have results from any time of previous day.
If Your Field AddDate is a DateTime Field you can do it as follows
using (var db = new DbContext())
{
var query = (from n in db.BDatas
orderby n.AddDate,n.CountryCode
where n.CountryCode=="GB"
select n).Where(n => n.AddDate.Date >= stdate.Date &&
n.AddDate.Date <= etdate).ToList();
}
Using Entity Framework Core
Had a Model "Fire", needed to pass date string to date from format "yyyy-MM-dd"
Injected my dbContext in my Service class
First cast date string to DateTime and used them to fetch records as shown below
var sDate = DateTime.ParseExact(startDate, "yyyy-MM-dd", CultureInfo.InvariantCulture);
var eDate = DateTime.ParseExact(endDate, "yyyy-MM-dd", CultureInfo.InvariantCulture);
var fireData = await _dbContext.Fire.Where(b => (b.CreatedAt >= sDate && b.CreatedAt < eDate) && b.UploadStatus == "False").ToListAsync();
return fireData;

Linq query DateTime.Date.DayOfWeek

Trying to get only Thursdays of 1 year back
using (var context = new Context1())
{
// Get 1 year back only Thursday
var oneYearEarlier = DateTime.Now.AddYears(-1);
var query = (from c in context.Daily25Data
where c.Date > oneYearEarlier && c.Date.DayOfWeek == DayOfWeek.Thursday
select c).ToList();
Console.WriteLine(query);
}
and getting
Additional information: The specified type member 'DayOfWeek' is not
supported in LINQ to Entities. Only initializers, entity members, and
entity navigation properties are supported.
This is a clever solution using EntityFunctions.DiffDays
from his post:
DateTime firstSunday = new DateTime(1753, 1, 7);
var bookings = from b in this.db.Bookings
where EntityFunctions.DiffDays(firstSunday, b.StartDateTime) % 7 == 1
select b;
LINQ will not recognize the second part of your query into SQL. You need to break your query up in order to perform the filter.
using (var context = new algoventurelab_db1Context())
{
// Go one year back from current date
var startDate = DateTime.Today.AddYears(-1);
// This will get all dates in context greater than start date.
var query1 = (from c in context.Daily25Data
where c.Date >= startDate
select c).AsEnumerable();
//this will filter only thurdays
var query = from c in query1
where c.Date.DayOfWeek == DayOfWeek.Thursday
select c).ToList();
Console.WriteLine(query);
}

linq to retrieve name instead of id and list in descending order

can u help me to solve this.
i'm retrieving the balance of each heads, and i retrieved the balance of each heads. Now i want to list the balance in the descending order and list the name instead of h_id. i used the code
protected void account_watchlist() {
using(var context = new sem_dbEntities()) {
//ledger && head
var year = DateTime.Now.AddMinutes(318).Year;
var month = DateTime.Now.AddMinutes(318).Month;
var start = new DateTime();
if (month >= 4) {
start = new DateTime(year, 04, 01);
} else if (month < 4) {
start = new DateTime(year - 1, 04, 01);
}
var qr = (from a in context.ledgers
where a.entry_date >= start && a.entry_date < new DateTime(year, month, 1)
join b in context.heads on a.h_id equals b.h_id
group a by a.h_id into sb select new {
sb.FirstOrDefault().h_id,
totalc = sb.Sum(c => c.credit),
totald = sb.Sum(d => d.debit),
balance = sb.Sum(d => d.debit) - sb.Sum(c => c.credit)
}).ToList();
Repeater2.DataSource = qr.ToList();
Repeater2.DataBind();
}
}
You need to use group join of heads with ledgers. It will give you access both to head entity and all related ledgers (in headLedgers collection):
from h in context.heads
join l in context.ledgers.Where(x => x.entry_date >= startDate && x.entry_date < endDate)
on h.h_id equals l.h_id into headLedgers
where headLedgers.Any()
let totalc = headLedgers.Sum(l => l.credit),
let totald = headLedgers.Sum(l => l.debit),
select new {
h.h_id,
h.name,
totalc,
totald,
balance = totald - totalc,
}
I also introduced two range variables for total credit and total debit (consider better names here) to avoid calculating them second time for balance.

how to select a weeks amount of dates from a database?

What I am trying to do is search my database (ado.net with linq to sql) for all entrys within the last week.
The database has a field called date and I need the entries that are 7 days previous to the current date.
var records = (from r in context.PumpInfoTables
where r.Date.Equals(DateTime.Now)
//&& where r.date <= 7 days <--help
select r);
so I am looking for some help with this query, is there a between function that can be used?
DateTime weekFromNow = DateTime.Now.AddDays(-7);
var records = (from r in context.PumpInfoTables
where r.Date < DateTime.Now
&& r.Date >= weekFromNow
select r);
This is really simple:
var oneWeekAgo = DateTime.Today.AddDays(-7);
var records = (from r in context.PumpInfoTables
where r.Date >= oneWeekAgo
select r);
This assumes that you don't have entries from the future. If you do have, use this instead:
var today = DateTime.Today;
var oneWeekAgo = today.AddDays(-7);
var records = (from r in context.PumpInfoTables
where r.Date >= oneWeekAgo && r.Date <= today + 1
select r);
Please note:
My code uses DateTime.Today instead of DateTime.Now, assuming you are only interested in the date part, not the time.
Something like this?:
var records = (from r in context.PumpInfoTables
where r.Date > DateTime.Today.AddDays(-7)
select r);

Getting number of records by date in LINQ to SQL query even if no results

I have written the following LINQ-to-SQL to enable me to get a total number of records by day.
There are a few modifications I'd like to make to it in order to have it fit my needs. I have made various attempts but haven't been able to get it right.
I'd like to list the last 9 days, even if there were no 'opens' during this time.
I'd also like to group by Day/Month instead of just Day as I'm doing below.
An example of the output I'd love to get would be:
DateString Opens
===================
9/5 0
10/5 0
11/5 3
etc...
public List<OpensOverTimeViewModel> GetOpensOverTimeViewModel(int eId)
{
DateTime lastDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).AddDays(-9);
DateTime currentDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).AddDays(1);
var summary = (from p in db.Opens
where (p.ElementId == eId) && (p.Timestamp >= lastDate) && (p.Timestamp <= currentDate)
let k = new
{
Day = p.Timestamp.Day
}
group p by k into t
select new OpensOverTimeViewModel
{
DateString = t.Key.Day,
TotalOpens = t.Count(),
ElementName = ""
}).ToList();
return summary;
}
Any help on how best to tackle this would be much appreciated.
You can create a left join in code after you got the result back from the database
Put the below lines just before your return summary; line.
var allDates = from idx in Enumerable.Range(0, (currentDate - lastDate).Days)
select lastDate.AddDays(idx);
summary = (
from allDate in allDates
join su in summary on allDate.Day equals su.DateString into x
from su in x.DefaultIfEmpty()
select new OpensOverTimeViewModel
{
DateString = allDate.Day,
TotalOpens = su == null ? 0 : su.TotalOpens,
ElementName = ""
}).ToList();
To group by day/month I suggest using the whole date, replacing t.Key.Day with t.Key.Date and changing DateString into a DateTime.

Categories