LINQ group by and compare date - asp.net

I have the following:
var currentDate = DateTime.UtcNow;
var calendarEntry = from item in new CalendarEntryRepository(this.Db).List().Where(x => x.Culture == language.Value)
group item by item.ContentObjectId into g
let itemMaxDate = g.Where(i => i.StartDate > currentDate).Select(i => i.StartDate).DefaultIfEmpty()
let city = g.Select(i => i.City).FirstOrDefault()
select new
{
ContentObjectId = g.Key,
StartDate = itemMaxDate,
City = city ?? string.Empty
};
From CalendarEntryRepository I want to group by ContentObjectId (this works fine). However when i add this line:
let itemMaxDate = g.Where(i => i.StartDate > currentDate).Select(i => i.StartDate).DefaultIfEmpty()
I keep getting this error:
Message = "The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value."
What i'm trying to do is group by ContentObjectId and then get StartDate that is greater than today.
I'm using entity framwork and MS SQL2008
thanks

The Min Value of DateTime in your database has a lower value that the MinValue defined int he culture you used in your App.

Change the StartDate column in DataBase to data type DateTime2 to support a broader range of dates

Related

firebase realtime DB: TypeError: Cannot convert undefined or null to object

I am having query like below
var db = admin.database();
var ref = db.ref('orders') ref.orderByChild("order/_date").startAt(begDate).endAt(endDate).once("value").then(
(resp) => {
..
}).catch(
(err) => console.log('failed in sales report:' + err)
)
it throws below
TypeError: Cannot convert undefined or null to object
The data looks like below
orders: {
"-LNMPXMb1SGSnkDaEMQO" : {
"order" : {
"_cgst" : "11.90",
"_date" : "1538368446413",
"_location" : "kapashera",
"_orderNumber" : "VikKumar-21247",
"_orderStatus" : "Delivered",
}
},
At the time of execution the begDate and endDate are:
begDate:1538352000000 endDate:1538438400000
So two problems:
1.The error itself. How can I avoid throwing error if no match?
2. Why is the above record not matching when the date value is between begDate and endDate?
You are probably doing the same error than in you other question of yesterday: firebase realtime DB querying date between 2 dates does not match anything
Therefore, the reason is probably because begDate and endDate are numbers but you store _date as a string in your database.
Try using toISOString when you save to fb
var _date = new Date().toISOString()
and
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth();
var day = d.getDate();
var begDate = new Date(year - 1, month, day).toISOString();
var endDate = new Date(year + 1, month, day).toISOString();

Linq To Sql Count By Time Brackets

I need a Linq To SQL Query that Counts the rows of a table that fall within time brackets of an arbitrary interval. The Table has a single DateTime field.
Google got me to this SQL (http://ebersys.blogspot.ca/2010/12/sql-group-datetime-by-arbitrary-time.html)
declare #interval int
set #interval = 5
select convert(varchar(8), DTColumn, 1)+' '
+convert(varchar(2), datepart(hh, DTColumn))+':'
+convert(varchar(2), datepart(mi, DTColumn)/#interval*#interval)
, count(*)
from the_table
group by convert(varchar(8), DTColumn, 1)+' '
+convert(varchar(2), datepart(hh, DTColumn))+':'
+convert(varchar(2), datepart(mi, DTColumn)/#interval*#interval)
I could move the query to SQL but prefer to keep the DAL consistent LinqToSQL. The best I could come up with is this, but errors with "Tick is not supported in SQL"
int interval = Convert.ToInt32(uxTxtInterval.Text);
var q = (from d in dc.theTable.OrderBy(o => o.dmMe).ThenBy(o => o.dmWith).ThenBy(o => o.dmCreatedAt)
group d by
(
Math.Floor(new TimeSpan(d.dmCreatedAt.Ticks).TotalMinutes / interval)
)
into grpTable
select
new
{
time = grpTable.Key, // ?? needs to be the DateTime not ticks
count = grpTable.Count()
}
);
Any help greatly appreciated :-)
Thanks!
You can use SqlMethods.DateDiffMinute to get the time buckets:
var startdate = new DateTime(1900,1,1); // An arbitrary date
int interval = Convert.ToInt32(uxTxtInterval.Text);
var q = (from d in dc.theTable.OrderBy(o => o.dmMe).ThenBy(o => o.dmWith).ThenBy(o => o.dmCreatedAt)
group d by
(
SqlMethods.DateDiffMinute(startdate, d.dmCreatedAt) / interval
)
into grpTable
select
new
{
time = grpTable.Key,
count = grpTable.Count()
}
);

Convert sql to entity in query syntax

How can i convert the following query to entity framework in query syntax..
SELECT MIN(Date) StartDate, MAX(Date) EndDate, Title, Flag FROM
Holiday GROUP BY Title, Flag
Any help?
After a hard time i get the solution
(from e in db.Holidays
group e by new {e.Title, e.Flag}
into g
select new AllEventViewModel
{
start = g.Max(e=>e.Date),
end = g.Min(e => e.Date),
title = g.Key.Title,
Flag = g.Key.Flag
}).AsEnumerable();
var results = db.holidays.GroupBy(g => new { g.Title, g.Flag }).Select(k => new
{
MinDate = k.Min(a => a.Date),
StartDate = k.FirstOrDefault().StartDate,
MaxDate = k.Max(b => b.Date),
EndDate = k.FirstOrDefault().EndDate,
Title = k.Key.Title,
Flag = k.Key.Flag
}).ToList();

Linq to Entity, selecting group with or without value

Hi Need some help with LINQ query.
I have entity called Shift. This entity has several value field but the ones I am intressted in are ShiftID (int), ShiftDate (DateTime) and GrossMount (decimal(10,2). And this needs to be grouped by month (binding this to a graph in ASP.NET).
I need data for the last 12 months grouped by month.
I have come a bit on the way with this post: Linq to Entity, selecting group without value but not quite all the way.
This is my code for now:
public IQueryable<Shift> GetPastMonths(int months, string accountNumber)
{
_context = new EtaxiEnteties();
var _date = DateTime.Today;
var _firstOfMonth = new DateTime(_date.Year, _date.Month, 31);
var _twelveMonthAgoFirstOfMonth = _firstOfMonth.AddMonths(-12);
// Generate a collection of the months and years for the last 12 months
var _monthYears = Enumerable.Range(-12, 12).Select(monthOffset => { var monthDate = _firstOfMonth.AddMonths(monthOffset); return new { y = monthDate.Year, m = monthDate.Month }; });
var _data = (from _monthYear in _monthYears
join _i in
(from _i in _context.Shifts.Where(acc => acc.Account.AccountNumber == accountNumber)
where _i.ShiftDate >= _twelveMonthAgoFirstOfMonth && _i.ShiftDate < _firstOfMonth
group _i by new { y = _i.ShiftDate.Year, m = _i.ShiftDate.Month } into g
select new { ShiftID = g.Key, GrossAmount = g.Count() }) on _monthYear equals _i.ShiftID into j
from _k in j.DefaultIfEmpty()
select new Shift() { ShiftDate = new DateTime(_monthYear.y, _monthYear.m, 1), GrossAmount = _k != null ? _k.GrossAmount : 0 });
return _data as IQueryable<Shift>;
}
Now I have in return a collection of Shift objects, grouped by month but still missing the GrossAmount. Althoug i would need this from today date (only getting from 1 of current month).
Believe this is my main problem: GrossAmount = g.Count(), but I am not sure
Any LINQ specialist out there that could give me a push?
Use GrossAmount = g.Sum(x => x.GrossAmount) to calculate total GrossAmount value of grouped Shift entities. I believe you have typo in GrossAmount (GrossMount) property name.

Entity Framework query syntax

I having a trouble with a query
I need to take out the SHIPMENT from GetAllOrderData - the same place where you can find POD_DATE and RECEIVE_NAME...but I get an error
Error 1 The name 'x' does not exist in the current context
My code is:
public IEnumerable<ReportItemDTO> GetTaskProgress(DateTime targetDate)
{
try
{
var startDate = targetDate.Date;
var endDate = startDate.AddDays(1);
OrderDataRepository rep = new OrderDataRepository();
var query = rep.GetAllOrderData()
.Where(x => x.POD_DATE >= startDate && x.POD_DATE <= endDate)
.GroupBy(o => o.User)
.Select(g => new ReportItemDTO
{
DriverId = g.Key.Id,
PdriverName = g.Key.Name,
OrderCount = g.Count(),
ReportedOrdersCount = g.Count(o => o.RECEIVE_NAME != null),
SHIPMENT = (x.SHIPMENT)
} );
return query;
SHIPMENT = (x.SHIPMENT)
Well you are within a grouping when you try to make that assignment - there are many shipments in each grouping not just one - in fact all shipments for that particular user. Assuming you want a collection of them you could do:
Shipments = g.Select( x=> x.SHIPMENT)
Edit:
If you just want the first shipment for each user (somewhat illogical but fits your data model):
SHIPMENT = g.Select( x=> x.SHIPMENT).First()

Resources