LINQ Query against Azure table service fails - c#

I have a few records saved in my Azure Table Storage. I'm trying to pull records from a table,for only a particular day/date, for the currently logged in user.
My query returns nothing, so my list is always empty, even though I know that I have 3 records for this month, in my table.
I'm not sure why the query fails in this case. How do I pull records for a specific date, for a specific user? Any help?
This is what I've tried so far:
public async Task<Result<List<Alert>>> FetchAlertsForDate (DateTime date)
{
try {
var fromDate = new DateTime(date.Year,date.Month,date.Day,0,0,0); //lets create a 12:00:00 AM date
var toDate = new DateTime(date.Year,date.Month,date.Day,23,59,59); //lets create a 23:59:59PM date
var alertTable=client.GetSyncTable<Alert>();
var alerts = await alertTable.Where(n=>n.AccountId==client.CurrentUser.UserId).Where(n=> n.StartDate >= fromDate && n.StartDate <= toDate).ToListAsync();
return Result<List<Alert>>.Success(alerts);
} catch (Exception ex) {
return Result<List<Alert>>.Failure (ex.Message + ex.StackTrace);
}
}

The code you have written contains no obvious bugs to answer your question
How do I pull records for a specific date, for a specific user?
Rather than a date range you use in your method you can just compare the date part of a dateTime like this;
var alerts = await alertTable.Where(n=>n.AccountId==client.CurrentUser.UserId).Where(n=> n.StartDate.Date == date.Date).ToListAsync();
I think you can do away with the second where clause too;
var alerts = await alertTable.Where(n=>n.AccountId==client.CurrentUser.UserId && n.StartDate.Date == date.Date).ToListAsync();
If you are not getting any records then for that specific combination of userId and Date then the most likely thing is that there aren't any records with that exact combination.

For some reason, the same query ended up working. I improved on it by removing the first part, where I was checking for the current user's id. That wasn't necessary since in my case.
So the final query looks like this:
var alerts = await alertTable.Where(n=> n.StartDate >= fromDate && n.StartDate <= toDate).ToListAsync();
This now pulls up all the logged in user's details.

Related

Is there any way to compare a list object and add specific items

I have a List which contains the order details of several users such as StoreId, OrderTotal, dateModified etc. I want to add the order total which fall under same date but different time.
Below is the code which fetches data from the database. Also I have attached the output which I am getting.
An example of what I am trying to do is: if there are 2 orders for 08/09/2020 then I want to add the orderValue. The third column in the image refers to order value.
public async Task<IActionResult> OnGet()
{
try
{
StoreOrderDetails = new List<Store_Order>();
StoreOrderDetails2 = new List<Store_Order>();
var res = await UOW.CurrentContext.StoreOrder
.OrderBy(x => x.OrderModified)
.ToListAsync();
foreach (var item in res)
{
if(item.Status.ToString() == "PaymentComplete" &&
item.StoreId == defaultStoreId)
{
StoreOrderDetails.Add(item);
}
}
totalCount = StoreOrderDetails.Count();
StoreId = defaultStoreId;
StoreOrderDetails.GroupBy(x => x.OrderModified).Select(grpData =>
new Store_Order
{
OrderModified = grpData.Key,
OrderTotal = grpData.Sum(item => item.OrderTotal),
});
}
catch
{
}
return Page();
}
If that first column in your image is the date you refer to in code when you say x => x.OrderModified, you'll need to group by only the date element, excluding the time:
StoreOrderDetails.GroupBy(x => x.OrderModified.Date).Select(grpData =>
^^^^^
When you group a date that has a time too, then events will go into different groups if they are even only a nanosecond different. If you want dates to group according to the day all different things happened on, then you have to group by the date without the time. The easiest way to do this is to ask for a DateTime's Date property - it's the date, but with the time of midnight. If you fake it as if all orders occurred at midnight, then the Sum will work out
Oh, and you'll actually need to store/use the results of the group operation...

Get Next Meeting Date fails using Linq query

I need to display the next Meeting Date from a table of meeting dates. Once a date passes as current, the next date is supposed to show up. I've searched for similar examples but no luck:
05/21/2019
07/11/2019
08/08/2019
09/12/2019
10/10/2019
11/14/2019
12/12/2019
Here the Linq query I have that fails. It doesn't return anything for example after the 10/10/2019 date because 11/14/2019 is actually more than 1 month.
var LinqResult = (from c in _context.MeetingSchedule
where c.MeetingDate.Date >= DateTime.Now.Date && c.MeetingDate.Date <= DateTime.Now.Date.AddMonths(1)
select new { c.Location, c.MeetingDate, c.MeetingTime }).ToArray();
if (LinqResult.Any())
{
//SEND NEXT MEETING DATE BACK VIA VIEWSTATE
}
Also, I am pretty sure something odd is going to happen on the last month of the year after the meeting happens (December).
I am trying to show the current next meeting, and have it change to the next meeting after that once the current one is over. Adding a month to 12 will create a month number 13 which is non-existent.
You can sort meeting schedule ascending after filtering out dates that have already happened then just grab the first one.
var LinqResult = (from c in _context.MeetingSchedule
where c.MeetingDate.Date >= DateTime.Now.Date
orderby c.MeetingDate.Date
select new { c.Location, c.MeetingDate, c.MeetingTime }).ToArray();
if (LinqResult.Any())
{
//SEND NEXT MEETING DATE BACK VIA VIEWSTATE
}

SQL to entities - complex query selecting dates

I'm using Entity Framework code-first and I want to query the appointments table in my database selecting:
All the appointments on given dates
public IEnumerable<Appointment> GetAppointments(IEnumerable<DateTime> datesWithEverything)
{
using (OneClickContext context = new OneClickContext())
{
var query = from e in context.AppointmentSet
where datesWithEverything.Contains(e.StartDate)
select e;
return query;
}
}
I also need only one appointment from any other day, the first found for each day not included in the given dates.
The reason for this, is that my calendar component will be able to show in bold the days containing at least one appointment, but I don't want to load thousands of appointments since I will be looking few days (with all the details) per request.
Is this possible hitting the database once?
Any help is appreciated.
If I understand your needs correctly, you are getting all appointment data for a range of dates, and then you simply need to know all other dates that have at least one appointment in order to bold them. You aren't actually using the appointment data on those other dates just yet. Is that correct?
You are right to try to limit the number of trips to the database, but you need to balance that with not returning more data than you actually need. If I understand right and all you need are dates with appointments, you should use a second query:
public IEnumerable<DateTime> GetDatesWithAppointments()
{
using (OneClickContext context = new OneClickContext())
{
var query = (from e in context.AppointmentSet
order by e.StartDate
select e.StartDate).Distinct();
return query.ToList();
}
}
Also, it's a matter of style but the variable "query" is not needed, and you can simply:
return (from e in context.AppointmentSet
order by e.StartDate
select e.StartDate).Distinct().ToList();
Note the ToList(). Linq query execution is deferred until the first time it is enumerated and your query context is declared in a using block. You must execute the query before the using block exits in this case.
On edit, since you require an actual appointment, you should be able to get what you want in a single trip using linq's union and grouping. Union will automatically remove any duplicate entries.
public IEnumerable<Appointment> GetAppointments(IEnumerable<DateTime> datesWithEverything)
{
using (OneClickContext context = new OneClickContext())
{
var query = from e in context.AppointmentSet
where datesWithEverything.Contains(e.StartDate)
select e;
query = query.Union(from e in context.AppointmentSet
group e by DbFunctions.TruncateTime(e.StartDate) into grp
select grp.FirstOrDefault());
return query.ToList();
}
}

LINQ to entites does not recognize Convert.ToDatetime method

EDIT All the other answers that link to a previous question's wont work for me because they are either using two tables or they know what startdate they are looking for.
I have the following LINQ query where i am trying to get the data from a table for the last 14 days. LINQ does not recognize Convert.ToDatetime method. The Query_Date column is a type string and i can't change it. How do i get the data i need?
var logs = (from bwl in db.UserActivities
where Convert.ToDateTime(bwl.Query_Date) >= DateTime.Now.AddDays(-14)
select new
{
Id = bwl.Id,
UserEmail = bwl.UserEmail
}).ToList();
So i couldn't get what i wanted because i would have to make too many changes so the workaround i am doing is: I am using this code
var logs = db.UserActivities.ToList().Take(100);
This will get me the last 100 entries. I will give options for more or less entries then they can filter it on date in the search bar on the datatable.
It's not great but time is against me and this will suffice.
Do you have data being entered at least every day? If so, what about something like this:
var oldestDate = DateTime.Now.AddDays(-14);
var dateString = oldestDate.ToString(*/ your date format */);
var oldestID = db.UserActivities.First(b => b.Query_Date == dateString).Id;
var logs = (from bwl in db.UserActivities
where bwl.Id > oldestID
select new {
Id = bwl.Id,
UserEmail = bwl.UserEmail
}).ToList();
Basically you find a record on that date and use its ID as a proxy for the date. This only works in certain circumstances (i.e. if the IDs are in date order).
This also isn't guaranteed to be the oldest entry on that date, but that could be achieved either by using ID order:
var oldestID = db.UserActivities.Where(b => b.Query_Date == dateString)
.OrderBy(b => b.Id)
.First().Id;
Or more lazily by using -15 instead of -14 when you add days, if you don't mind grabbing an unknown percentage of that 15th day.
Convert.ToDateTime works if your Query_Date has proper format. If not, check your string expression is convertable format.
I tested below code and it works fine when I assume Query_Date is a form of DateTime.toString().
var logs = (from bwl in db.UserActivities
where DateTime.Now - Convert.ToDateTime(bwl.Query_Date) <= TimeSpan.FromDays(14)
select new
{
Id = bwl.Id,
UserEmail = bwl.UserEmail
}).ToList();
I also tested with your where expression Convert.ToDateTime(bwl.Query_Date) >= DateTime.Now.AddDays(-14) and confirmed that it gives same result.

Show data between a date range

Greetings
I have the personal data of an individual including birth date
How do I get the information of people born between the date 1 and date 2?
date of birth is in a SQL Server database Compact
I get a record this way
using (ISession session = NHibernateConfiguration.OpenSession())
{
var production = session
.CreateCriteria(typeof(Person))
.Add(Restrictions.Eq("Date", date))
.List<Person>();
return production;
}
instead of .Add(Restrictions.Eq("Date", date)) use .Add(Restrictions.Between("Date", fromDate, toDate))
If you have these Object's Stored on a List than you could say ,
for(int i=0;i<list.count;i++)
{
if(list[i].getBirthdate.Day == 1 || list[i].getBirthdate.Day == 2 )
//DoSomething
}
But man ,you should be more Specific ,if these Information's are Stored in DataBase ,if Birth Date is Stored As Formated DateTime or whatever ,please be more specific and show us some code.
By the tags in your question, it looks like you're using Nhibernate. If you use Linq-to-Nhibernate, then you could use a linq statement like this:
var query = myISession.Linq<Person>();
var result = from entity in query
where entity.Dob >= dob1 && entity.Dob <= dob2
select entity;
return result.Count() > 0 ? result.ToList() : null;
I like extensions methods much more
var persons = GetPersonList();
var range = persons.Where(p => p.Dob >= startDate && p.Dob <= endDate);
Note that I know this is basically the same as using LINQ syntax, I just don't like linq syntax :).

Categories

Resources