In LINQ to SQL, how do I compare only the date part of an sql datetime column and .net datetime object?
Try using the Date property of both:
Date today = DateTime.Today; // Effectively DateTime.Now.Date
var dataFromToday = from record in context.Records
where record.TimeStamp.Date == today
select record;
I believe this works for LINQ to SQL... as tvanfosson says, it doesn't for EF.
Linq to SQL supports translation of the Date property to SQL for comparisons, etc. More information on the supported options can be found on MSDN.
using System.Data.Entity;
DbFunctions.TruncateTime(u.BirthDate) = DbFunctions.TruncateTime(someDate)
You could create a CLR UDF to do the date only compare and then reference that in your linq to sql linq query.
using System.Data.Objects.SqlClient; //Don't forget this!!
//You can access to SQL DatePart function using something like this:
YourTable.Select(t => new { DayOfWeek = SqlFunctions.DatePart("weekday", t.dateTimeField) - 1 }); //Zero based in SQL
//You can compare to SQL DatePart function using something like this:
DateTime dateToCompare = DateTime.Today;
YourTable.Where(t => SqlFunctions.DatePart("weekday", t.dateTimeField) - 1 == dateToCompare }); //Zero based in SQL
Related
Hi I am trying to write linq query to get some details from Sql table. I have created column and storing date and time both. while returning i want to ommit time part. May I know is this possible?
List<returnObject> obj = new List<returnObject>();
obj = (from c in objectDB.NCT_Project
join user in objectDB.NCT_UserRegistration on c.adminUserId equals user.User_Id
where c.adminUserId == userId
select new returnObject
{
id = c.project_Id,
key = c.key,
created = c.createdDate //currently returns datetime
}).ToList();
Any help would be appreciated. Thank you.
Use DbFunctions.TruncateTime method:
created = DbFunctions.TruncateTime(c.createdDate)
According to the docs:
When used as part of a LINQ to Entities query, this method invokes the
canonical TruncateTime EDM function to return the given date with the
time portion cleared.
All you need to do is call 'Date' property on createdDate.
select new returnObject
{
id = c.project_Id,
key = c.key,
created = c.createdDate.Date
}).ToList();
you can try this one.
created = c.createdDate.ToString("HH:mm")
created = c.createdDate.ToString("H:mm")
created = c.createdDate.ToString("hh:mm tt")
created = c.createdDate.ToString("h:mm tt")
also see this question : How to get only time from date-time C#
If you can get date comparison out of the LINQ and leave the rest there, you can use this syntax:
sqlite.Query<Entity>("date comparison").Where("other queries")
The predicate I used in the Query() function had to return only todays orders and looked something like this:
select * from Order where date(orderDate/ 10000000 - 62135596800, 'unixepoch') = date('now')
i have to compare a choosen Date from a Calendar (startdat & enddat) with a Date in my SQL 2008 R2 DB. I have to write it with LINQ, but in the view i have, the DateTime is converted to a String (Varchar) so i have to convert it in my LINQ Query back to DateTime. My basic Query looks like this now:
var reportlist = (from r in context.Monthly_Report
where r.CreateDate >= startdat && r.CreateDate <= enddat
select r.Ticketnumber).ToList();
So the CreateDate i get is a String and for comparing i've to convert it. I've tried it with Convert.ToDateTime() but there's is the Problem with L2E.
So how can i convert it like in a SQL Script or that SQL knows what i means?
Thanks for every help i get. (btw i'm not allowed to change the view)
You can only use a reduced set of functions in Linq to Entities. This functions will be transalated to DB functions.
You can use:
canonical functions: they're availabel for all the providers (DB tastes)
entity functions: exposes canonical functions in the EDM
db functions: exposes canonical functions in the EDM
sql functions: exposes SQL Server specific functions
None of these groups includes a function that can convert from string to datetime, so there is no way to do it directly.
You must look for alternatives:
Create a DB view which exposes the "stringified" datetime as a datetimecolumn and query it
Create a stored proc and use it
Convert the datetime to string and compare it, if at all possible (this depends on how the "stringified" datetime looks like)
You can use the previous solution using substrings (which will map to DB functions). This will work for all cases: reorder the y, m, d, of the "stringified" dt date, so that it looks like "yyyymmdd". Then convert your startdat and enddat to the same format, and compare it in string (alphabetic) order.
Fundamentally, you need your view to return a datetime.
However, there are a couple of ways to do this.
1) You could pull your data out as a string into a list object. Then you wouldnt be using L2E.
var temp = (from r in context.Monthly_Report
select new { r.Ticketnumber, r.CreateDate} ).ToList();
var reportList = temp.Where(r =>
Convert.ToDateTime(r.CreateDate) >= startdat &&
Convert.ToDateTime(r.CreateDate) <= enddat)
2) You could convert your datetime to a string value and compare it.
var reportlist = (from r in context.Monthly_Report
where r.CreateDate.CompareTo(startdatasstring) >= 0 &&
r.CreateDate.CompareTo(enddatasstring) <= 0
select r.Ticketnumber).ToList();
I am using Sql-Server 2012 and have a query
string sqlQuery = "SELECT distinct DATE_FORMAT(collectiondate,'%m/%d/%Y') FROM reports where patientid= " + patientId + " and isdeleted=false order by collectiondate desc";
var lst = Session.CreateSQLQuery(sqlQuery).List();
ArrayList rpt = new ArrayList();
rpt.Add("--ALL--");
but I am getting an error
System.Data.SqlClient.SqlException: 'DATE_FORMAT' is not a recognized built-in function name.
Can someone help me out?
You should rather try using CONVERT
SELECT CONVERT(VARCHAR(8),GETDATE(),1)
SQL Fiddle DEMO
That being said, I would recomend returning the values as is from the Database, and leaving the formatting to the UI.
There's no DATE_FORMAT function in SQL Server.
You need to use CONVERT function
SELECT distinct SELECT CONVERT(VARCHAR(8), collectiondate, 1) ...
Also, formatting is best to be done in the code, not in SQL Server. You should return your date as DATE or DATETIME column and format it in your code.
You can use the FORMAT() command in SQL Server 2012 instead.
DECLARE #d DATETIME = GETDATE();
SELECT FORMAT(#d, 'mm/dd/yy', 'en-US') AS 'Result';
I have the following SQL statement to be converted into LINQ in C#. The #amount variable will be a C# variable.
DECLARE #amount DECIMAL(20,2)
SET #amount = 120.30
UPDATE INVOICES SET AmtPaid = AmtPaid + #amount WHERE InvoiceNum = 'AC0000034550'
You cannot UPDATE with LINQ.
LINQ is a query engine, suitable for SELECT (if we talk in terms of raw SQL).
Plus, if you already have good working SQL code, it does not make any sense to convert it into LINQ; SQL is faster, and works.
why dont you make a select with linq an then iterate over the list and update the variable??
LINQ does not do updates,so you cannot convert the SQL to LINQ
I did as follows. Not sure whether it is correct or not:
using (var dataContext = GetDataContext())
{
var invoiceData = from i in dataContext.Invoices
where i.InvoiceNumber == paymentData.InvoiceNumber
select i;
foreach(var invoice in invoiceData)
{
decimal outPut;
if (Decimal.TryParse(paymentData.AmountPaid, out outPut))
{
invoice.AmtPaid = invoice.AmtPaid + Convert.ToDecimal(paymentData.AmountPaid);
}
}
dataContext.SubmitChanges();
}
I'm wanting to call this stored procedure with input parameters:
proc [dbo].[Invoice_GetHomePageInvoices] (
#FinancialYearStartDate datetime = null
, #FinancialYearEndDate datetime = null
Trouble with this is the way I usually call a stored proc from my code is:
return _db.Database.SqlQuery<HomePageInvoice>(string.Format("EXEC Invoice_GetHomePageInvoices #FinancialYearStartDate = '{0}', #FinancialYearEndDate = '{1}'", financialYear.StartDate.ToString(), financialYear.EndDate.ToString()));
So this isn't going to work because I've basically converted my datetimes to strings.
How the heck am I supposed to do this?
You should use sql parameters, basically like this:
var startDate = new SqlParameter("FinancialYearStartDate", dateTimeValueHere);
var endDate = new SqlParameter("FinancialYearEndDate", dateTimeValueHere);
return _db.Database.SqlQuery<HomePageInvoice>("Invoice_GetHomePageInvoices", startDate, endDate);
More info: How to use DbContext.Database.SqlQuery<TElement>(sql, params) with stored procedure? EF Code First CTP5
convert the date to a string with specific format.
use SQL code to convert it back to an sql datetime object.
When using sql server (microsoft):
http://msdn.microsoft.com/en-us/library/ms187928.aspx
"convert(datetime, '{0}', 103)", financialYear.EndDate.ToString("MM/dd/yyyy")
edit: Ropstah's method is actually better, this is just the way I used to do it :P