Anyone know how to query for a specific date within entity framework ? I tried following code, but it gives me NotSupportedException.
var deposit = (from tempDeposit in entities.Deposit
where !tempDeposit.IsApproved
&& tempDeposit.CreatedDate.Date == DateTime.Today
select tempDeposit).FirstOrDefault();
I also tried following code but still gave me NotSupportedException.
var deposit = (from tempDeposit in entities.Deposit
where !tempDeposit.IsApproved
&& tempDeposit.CreatedDate.ToFullString() == DateTime.Today.ToFullString()
select tempDeposit).FirstOrDefault();
ToFullString() is an extension method
public static string ToFullString(this DateTime date){
return date.ToString("yyyyMMdd");
}
Please help.
Try this:
var d1 = DateTime.Today;
var d2 = d1.AddDays(1);
var deposit = (from tempDeposit in entities.Deposit
where !tempDeposit.IsApproved
&& tempDeposit.CreatedDate >= d1
&& tempDeposit.CreatedDate < d2
select tempDeposit).FirstOrDefault();
Since you can't use the .Date property of a DateTime column, since that would have to be written in SQL with a range of converts, casts, truncates, etc. then you need to compare the whole DateTime value, date and time both, to a value, and thus you need to compare to a range.
Edit Changed to reflect that .AddDays isn't supported.
Well, after sometime tried, I found the solution
var deposit = entities1.Deposit
.Where("CreatedDate >= #0 and CreatedDate < #1", DateTime.Today, DateTime.Today.AddDays(1))
.FirstOrDefault();
Related
I am trying to execute the following code and am receiving an error
public List<Log> GetLoggingData(DateTime LogDate, string title)
{
var context = new LoggingEntities();
var query = from t in context.Logs
where t.Title == title
&& t.Timestamp == LogDate
select t;
return query.ToList();
}
The error I'm receiving is "The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported." I have tried various attempts of casting everythign to a string, only comparing the date part, but can't seem to get the right combinaation. Any help is greatly appreciated.
If you are using EF 6.0+, you can use DbFunctions.TruncateTime(DateTime?) :
var query =
from t in context.Logs
where t.Title == title
&& DbFunctions.TruncateTime(t.Timestamp) == LogDate.Date
select t;
Note: For earlier version of EF where DbFunctions isn't available, EntityFunctions.TruncateTime(DateTime?) can be used instead.
Not the greatest solution, but it works. For a variety of reasons, I have to use .net 3.5 at this point and modifying the database would be difficult. Anyways, here is a solution that works:
var query = from t in context.Logs
where t.Title == title
&& t.Timestamp.Day == LogDate.Day
&& t.Timestamp.Month == LogDate.Month
&& t.Timestamp.Year == LogDate.Year
select t;
Not the most elegant solution, but it is effective.
EntityFunctions.TruncateTime(t.Timestamp) is obsolete from EF6.
Use below
DbFunctions.TruncateTime(t.Timestamp)
Always use EntityFunctions.TruncateTime() for both x.DateTimeStart and LogDate.
such as :
var query = from t in context.Logs
where t.Title == title
&& EntityFunctions.TruncateTime(t.Timestamp) == EntityFunctions.TruncateTime(LogDate)
select t;
Correct me if I'm wrong, but in mikemurf22's example, it would need to check each part of the date component, and potentially a lot more server processing?
Anyway, I stumbled across this problem, and this is my solution.
Assuming that you're going to be passing in the date component only, you can find the last minute of the day that you pass in, and use the where clause to define the range.
public List<Log> GetLoggingData(DateTime LogDate, string title)
{
DateTime enddate = new DateTime(LogDate.Year, LogDate.Month, LogDate.Day, 23, 59, 59)
var query = from t in context.Logs
where t.Timestamp >= date
where t.Timestamp <= enddate
select t;
return query.ToList();
}
Convert LongDate to .ToShortDateStringand then you can use it this way:
EntityFunctions.TruncateTime(t.Timestamp) == LogDate
like mike did
Try this:
var calDate = DateTime.Now.Date.AddDays(-90);
var result = return (from r in xyz where DbFunctions.TruncateTime(r.savedDate) >= DbFunctions.TruncateTime(calDate)
You can use this hack:
DateTime startDate = LogDate.Date;
DateTime endDate = LogDate.Date.AddDays(1);
var query = from t in context.Logs
where t.Title == title
&& t.Timestamp >= startDate
&& t.Timestamp < endDate
select t;
I'm attempting to access data from two different database tables and then join them together on two fields using LINQ in C#. I believe that I have a logically sound overall working approach. Part of the problem I'm running into is that I'm filtering the data from both tables prior to joining them, because the tables have far too much data and it would cause a crash.
The main problem is that for one of the tables I need to pull only data that has a timestamp (column) value of today. The timestamp value is of type System.DateTime?.
I've tried a few different ways:
DateTime? currentDate = System.DateTime.Now;
var second_data = (from b in this.database.table
where EntityFunctions.DiffDays(b.timeStamp.Value, currentDate) == 0
select b);
I'm under the impression this doesn't work because there's no function in the database to handle it. Inner Exception: '{"FUNCTION database.DiffDays does not exist"}'
var second_data = (from b in this.database.table
where b => b.timeStamp.Value.Date == DateTime.Now.Date
select b);
This doesn't work because 'The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.'
var second_data =
this.database.table.Where(sd => sd.timeStamp.Value.Date == DateTime.Now.Date);
But this again fails because of the use of .Date.
Unfortunately, because I don't have the memory to hold all that data, the possibility of of pulling all the data first and then running date logic on it is out of the question. If anyone could give any insight on how I might be able to solve this problem it would be greatly appreciated, thank you.
To get rows from the table that are only for today (or a specific date range), you could simply do this. The nice thing about this approach is that it works for both cases of a specific date or a date range.
// specify date range (without time)
DateTime currentDate = System.DateTime.Now.Date;
DateTime nextDate = currentDate.AddDays(1);
var second_data = from b in this.database.table
where b.timeStamp.Value >= currentDate
and b.timeStamp.Value < nextDate
select b;
query = query.Where(c=> DbFunctions.DiffDays(c.ToDate, DateTime.Now) < 30);
Its not working in my scenario
I'm using Sql Server and I get your first method to work if I remove the call to timestamp.Value. I don't think your version compiles because DiffDays takes nullable DateTimes for both parameters.
DateTime? currentDate = System.DateTime.Now;
var second_data = (from b in this.database.table
where EntityFunctions.DiffDays(b.timeStamp, currentDate) == 0
select b);
The other thing I note is that I get a warning:
'System.Data.Entity.Core.Objects.EntityFunctions' is obsolete: 'This
class has been replaced by System.Data.Entity.DbFunctions.'
So if it still doesn't work in MySql you could try DbFunctions instead
this answer helped me for the exact day number, not in-between difference:
Found it on forums.asp.net
Here's a sample showing one way to get all employees with a DOB between now and 14 days from now...
var employeesWithBirthday =
from emp in dc.Employees
let BirthdayDiff = (new DateTime(DateTime.Now.Year, emp.BirthDate.Month, emp.BirthDate.Day) - DateTime.Now).TotalDays
where BirthdayDiff >= 0 && BirthdayDiff <= 14
select emp
;
...although, be aware that a query like that will do a table scan (can't use any indexes)...
I am trying to execute the following code and am receiving an error
public List<Log> GetLoggingData(DateTime LogDate, string title)
{
var context = new LoggingEntities();
var query = from t in context.Logs
where t.Title == title
&& t.Timestamp == LogDate
select t;
return query.ToList();
}
The error I'm receiving is "The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported." I have tried various attempts of casting everythign to a string, only comparing the date part, but can't seem to get the right combinaation. Any help is greatly appreciated.
If you are using EF 6.0+, you can use DbFunctions.TruncateTime(DateTime?) :
var query =
from t in context.Logs
where t.Title == title
&& DbFunctions.TruncateTime(t.Timestamp) == LogDate.Date
select t;
Note: For earlier version of EF where DbFunctions isn't available, EntityFunctions.TruncateTime(DateTime?) can be used instead.
Not the greatest solution, but it works. For a variety of reasons, I have to use .net 3.5 at this point and modifying the database would be difficult. Anyways, here is a solution that works:
var query = from t in context.Logs
where t.Title == title
&& t.Timestamp.Day == LogDate.Day
&& t.Timestamp.Month == LogDate.Month
&& t.Timestamp.Year == LogDate.Year
select t;
Not the most elegant solution, but it is effective.
EntityFunctions.TruncateTime(t.Timestamp) is obsolete from EF6.
Use below
DbFunctions.TruncateTime(t.Timestamp)
Always use EntityFunctions.TruncateTime() for both x.DateTimeStart and LogDate.
such as :
var query = from t in context.Logs
where t.Title == title
&& EntityFunctions.TruncateTime(t.Timestamp) == EntityFunctions.TruncateTime(LogDate)
select t;
Correct me if I'm wrong, but in mikemurf22's example, it would need to check each part of the date component, and potentially a lot more server processing?
Anyway, I stumbled across this problem, and this is my solution.
Assuming that you're going to be passing in the date component only, you can find the last minute of the day that you pass in, and use the where clause to define the range.
public List<Log> GetLoggingData(DateTime LogDate, string title)
{
DateTime enddate = new DateTime(LogDate.Year, LogDate.Month, LogDate.Day, 23, 59, 59)
var query = from t in context.Logs
where t.Timestamp >= date
where t.Timestamp <= enddate
select t;
return query.ToList();
}
Convert LongDate to .ToShortDateStringand then you can use it this way:
EntityFunctions.TruncateTime(t.Timestamp) == LogDate
like mike did
Try this:
var calDate = DateTime.Now.Date.AddDays(-90);
var result = return (from r in xyz where DbFunctions.TruncateTime(r.savedDate) >= DbFunctions.TruncateTime(calDate)
You can use this hack:
DateTime startDate = LogDate.Date;
DateTime endDate = LogDate.Date.AddDays(1);
var query = from t in context.Logs
where t.Title == title
&& t.Timestamp >= startDate
&& t.Timestamp < endDate
select t;
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 :).
Please help.
I am trying to figure out how to use DATE or DATETIME for comparison in a linq query.
Example:
If I wanted all Employee names for those who started before today, I would do something like this in SQL:
SELECT EmployeeNameColumn
FROM EmployeeTable
WHERE StartDateColumn.Date <= GETDATE() //Today
But what about linq?
DateTime startDT = //Today
var EmployeeName =
from e in db.employee
where e.StartDateColumn <= startDT
The above WHERE doesn't work:
Exception Details: System.NotSupportedException: The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
Use the class DbFunctions for trimming the time portion.
using System.Data.Entity;
var bla = (from log in context.Contacts
where DbFunctions.TruncateTime(log.ModifiedDate)
== DbFunctions.TruncateTime(today.Date)
select log).FirstOrDefault();
Source: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/84d4e18b-7545-419b-9826-53ff1a0e2a62/
That should work. Are you sure that there isn't another part of the query that triggered the exception? I have several instances of queries of the form
var query = from e in db.MyTable
where e.AsOfDate <= DateTime.Now.Date
select e;
in my code.
It may be due to the date in the database being nullable. Try this:
var EmployeeName =
from e in db.employee
where e.StartDateColumn.Value <= startDT
You can check the condition like this
var nextDay = DateTime.Today.AddDays(1);
var query = from e in db.MyTable
where e.AsOfDate >= DateTime.Today && e.AsOfDate < nextDay
select e;
here you'll get the records on AsOfDate date as we checking between today(00:00:00) and tommorow(00:00:00) we'll get today's date record only what ever may be the time...
You can not use .Date
If you would like to check for today you can create a datetime with no time
DateTime myDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
var e = (from mds in myEntities.Table
where mds.CreateDateTime >= myDate
select mds).FirstOrDefault();
try this:
DateTime dd = DateTime.Parse("08/13/2010 00:00:00");
var data = from n in ContributionEligibilities
where n.ModifiedDateTime.Date >= DateTime.Parse("08/13/2010").Date
select n;
data.Dump("Result") ;
I'm curious to the error message saying 'Date', when you're passing a 'DateTime'. Could it be that 'StartDateColumn' is actually a 'Date', rather than a 'DateTime' in the database? That might mess up the comparison...
use a local variable to store the Date value and then use that variable in the query:
DateTime today = DateTime.Now.Date;
from scheme in context.schemes
where scheme.EndDate > today
select scheme
I am using a LinqDataSource and I had problems getting my query with a Date Comparison in it to execute without errors. The answer is to use the WhereAddParameters function and add the test value as a strongly typed parameter.
See the example below where I am matching a groupid and checking to see if the StopDate in my record is greater that or equal to a Date/Time stamp of now.
I am using this code fragment currently and it works like a charm.
LinqCampaigns.WhereParameters.Add("StopDate", System.Data.DbType.Date, DateTime.Now.ToString())
LinqCampaigns.Where = "GroupId = " & myGrp & " && " & "StopDate >= #StopDate"
Works like a charm....
.Date did not work, but .Day did for me.
var query = from o in Payments
where o.Order.OrderDate.Day != o.PaymentDate.Day
orderby o.Order.OrderDate
select new
{
o.Order.OrderID,
o.Order.OrderDate,
o.PaymentDate,
o.Order.FirstName,
o.Order.LastName,
o.Order.CustomerID
};
query.Dump();
ensure that you check null value like this :
'(from mm in _db.Calls
where mm.Professionnal.ID.Equals(proid)
&& mm.ComposedDate.HasValue &&
(mm.ComposedDate.Value >= datemin) && (mm.ComposedDate.Value <= date)
select mm).ToArray();'