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')
Related
I'm trying to retrieve all fields from two joined tables to any kind of a c# object.
So I'm trying to run this code:
var query = #$"EXEC('select *
from persons p join students s on p.id=s.id
where p.id = 21')";
var result = _context.Database.SqlQuery<?>(query).ToList();
But I don't get what should be instead of the question mark.
I've tried List<object> and Dictionary<string,string> but since I couldn't get exactly how this is being mapped, I don't understand to what it can be mapped.
There is a somewhat similar question here but its solution only addresses two columns, and it apparently doesn't support returning nulls.
You can try creating a stored procedure or a function in the SQL level.
Then, just select then generated table / result.
So, you already have an idea of what class it is.
I frequently use the dynamic type like this :
var lst = _context.Database.SqlQuery<dynamic>(query).ToList();
foreach (var item in lst)
{
var myVar = item.myfieldName;
}
It may be preferable to name each field in your query instead of using select *.
I am using Npgsql 3.0.3.0 and PetaPoco latest version.
When I run this command:
var dateCreated = DateTime.Now; // just an example
var sql = new Sql("WHERE date_created = #0", dateCreated.ToString("yyyy-MM-dd HH:00:00"));
var category = db.SingleOrDefault<Category>(sql);
I get the following error:
Npgsql.NpgsqlException 42883: operator does not exist: timestamp
without time zone = text
I understand the error message is saying I'm trying to compare a timestamp (date) with a text, however for me it's perfectly valid to compare them as I am expecting the following SQL statement to be built:
SELECT * FROM category WHERE date_created = '2017-02-03 15:00:00'
I don't really want to typecast my database column to text for performance reasons.
You need to cast value to timestsamp:
var sql = new Sql("WHERE date_created = #0::timestamp", dateCreated.ToString("yyyy-MM-dd HH:00:00"));
You need to explicit typecast text to timestamp.
Try using :
TO_TIMESTAMP(date_string,'YYYY-MM-DD')
As #roman-tkachuk answered, you can tell PostgreSQL to cast your string into a timestamp.
Or better yet, you can simply send a timestamp to PostgreSQL directly, rather than sending a string representation of a timestamp and having it cast. To do that, simply send dateCreated directly, without the ToString().
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 have some data retrieved from a database which I hold in a data table.
What I want to do is extract only records that have a match to the date passed as a parameter only if it's greater than DateTime.MinValue(). This should be easy.
Below is the code snippet of how I build the query string. I know that if I don't have the date filter I get 'x' records but I always get 0 with the date filter.
string query = string.Format("Field_Name IN( 'GENDER','DOB','MARITAL_STATUS','SS') AND DIFF_TYPE = 'PER' AND Person_ID = '{0}'", Person_ID);
if (ChangeDetected > DateTime.MinValue)
{
query += string.Format(" AND ChangeToDT = #{0}#", ChangeDetected);
}
ChangeDataSet.DifferencesRow[] perChanges = this.m_ChangeDS.Differences.Select(query, "ChangeFromDT ASC, Field_Name DESC") as ChangeDataSet.DifferencesRow[];
I have tried all sorts of variations on outputting format for the DateTime in the filter but they all have the same result.
I don't know enough LINQ to do the conditional filter that way either. {:o(
Try specifying the format directly:
query += string.Format(" AND ChangeToDT = #{0}#", ChangeDetected.ToString("MM/dd/yyyy"));
BTW: This has nothing to do with LINQ.
I a have a simple linq to sql query and for some reason the .take() doesn't work. I tried to add skip() as well thinking that maybe it needed some starting point from where to take the records but the results are still same and rather than taking only 10 records, it takes all 240 records.
Would appreciate if somebody can tell me what's going on. Thanks in advance.
The code is:
var types = (from t in EventTypes.tl_event_types
select new
{
type_id = t.event_type_id,
type_name = t.type_name
}).Take(10);
I'm assuming that by naming conventions that EventTypes is your object. You need to select from your data context... So
var types = (from t in dataContext.EventTypes.tl_event_types
select new
{
type_id = t.event_type_id,
type_name = t.type_name
}).Take(10);
should work.