How to use UK-format date in linq with operators - linq

i have got a big problem with converting dates in c#,i want to query using LINQ,in my condition i have to put date,if i put DateTime its in american format and database which expecting UK format does not recognize the date,if use ToString('dd,MM,yyyy') to get british format,i cant use string in LINQ condition,what should i do?
var rslt=(from t in cr.table1
join v in cr.errorCatGroup
on t.m_error_id equals v.m_error_id
where t.m_date >= myDateTime1 && t.m_date <= myDateTime2
select new {
GroupName=t.Error
}).ToList();
i get mDateTime1 and myDateTime2 like :
CultureInfo ukCulture = new CultureInfo("en-GB");
DateTime myDateTime1 = DateTime.Parse("30/09/2018", ukCulture.DateTimeFormat);
DateTime result12 = DateTime.ParseExact("01-10-2018", "d-M-yyyy", CultureInfo.CurrentCulture);
so whats the right way of using it in LINQ

Related

LINQ - To Get Year from Date which is of Type String

I have this LINQ query:
hdms = from t in db.HOLIDAY
join t1 in db.EMPLOYEE on t.UPDATED_BY equals t1.EMP_CODE
where
t.HOLIDAY_NAME == searchtext &&
t.DOH.Value.Year == 2016
orderby
t.DOH
select new HOLIDAYDETAILS
{
HOLIDAY_NAME = t.HOLIDAY_NAME,
DOH = t.DOH,
EMP_NAME = t1.EMP_NAME
};
While executing this, below error occurs:
'string' does not contain a definition for 'Value' and no extension method 'Value' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
Error comes under Value in t.DOH.Value.Year = 2016.
Here type of t.DOH is string and value is 2016-04-14
I have also tried this one:
hdms = from t in db.HOLIDAY
where
DateTime.ParseExact(t.DOH, "yyyy-MM-dd", CultureInfo.InvariantCulture).Year == DateTime.Now.Year
orderby
t.DOH
select new HOLIDAYDETAILS
{
DOH = t.DOH
};
Now got this error:
LINQ to Entities does not recognize the method 'System.DateTime ParseExact(System.String, System.String, System.IFormatProvider)' method, and this method cannot be translated into a store expression.
Is there any other way to convert string to date type in LINQ?
Since DOH is of type string you could use StartsWith to check if the string starts with 2016.
where
t.HOLIDAY_NAME == searchtext &&
t.DOH.StartsWith("2016")
A better option would be to change your datatype of DOH to DateTime/DatetTime?, to get better support when working with date and time values. Then you can leave your query as it is.
You can parse DateTime from string like:
DateTime.ParseExact(t.DOH, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Then you can get year value using [DateTimeVariable].Year

How to convert a string into a datetime in Linq to Entities query?

My Linq to entities query is written as below.
The datatype of DATECOLUMN1 in my ORACLE database is of string.
Datetime FilterStartDate = DateTime.Now;
var query = from c in db.TABLE1
join l in db.TABLE2 on c.FK equals l.PK
where (FilterStartDate >= DateTime.ParseExact(l.DATECOLUMN1, "dd/MM/yyyy", CultureInfo.InvariantCulture) : false) == true
select c;
Writing above query gives me an error of not supported. How can I convert DATECOLUMN1 into a datetime to compare it.
P.S. I do not have control over database schema, so changing datatype of column in Oracle database is not a feasible solution for me.
In you Model, add the following property to your partial class TABLE2:
public DateTime DATECOLUMN1_NEW
{
get
{
return DateTime.ParseExact(DATECOLUMN1, "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
set { }
}
Then, in you LINQ query, use DATECOLUMN1_NEW (it's already in DateTime format) in place of DATECOLUMN1.
Erm.. I think the problem you are having is that you are putting ": false" in there.
It looks like you are trying to use a condtional operator (?:) but you forgot the "?".
I don't think you actually need this as you are just trying to determine if the date is greater or not. Also if ParseExact fails it will throw an exception (not what you want) so you should use TryParse instead and handle the true/false returned and the out value to determine whether or not the date is (a) Actually a date (b) less then FilterStartDate.
You can use two alternatives:
Use the function described in the answer here: How to I use TryParse in a linq query of xml data?
Use the following fluent syntax version which I think is more readable.
var query = db.Table1.Join(db.Table2, x => x.FK, y => y.PK, (x, y) => x).Where(x =>
{
DateTime Result;
DateTime.TryParse(x.Date, out Result);
return DateTime.TryParse(x.Date, out Result) && FilterStartDate >= Result;
});

Printing Month Name in Linq

Is there any Inbuilt function in Linq to Print the month Name while working with LINQPAD?
I want to print the month name in the following Scenario
var query = from e in Employees
let month=e.BirthDate.GetValueOrDefault()
let birthmonth=month.ToString("MMMM")
select birthmonth;
query.Dump();
When I run this it is throwing NotSupportedException.
how to print the month name in Linq to Sql?
Rather than using ToString, try string.Format. Something like:
var query = (from e in Employees
let month = e.BirthDate.GetValueOrDefault()
let birthmonth = string.Format("{0:MMMM}", month)
select birthmonth);
query.Dump();
This seems to work from my local testing, although it is not included as part of the SQL query.
Do it in two steps, one to get the months from the database, then another using Linq-To-Objects to perform the formatting.
var birthDates = Employees.Select(e => e.BirthDate).ToList();
var query = birthDates.Select(d => d != null ? d.ToString("MMMM") : "Null");
query.Dump();
Whatever ORM you are using can't convert the string formatting part of you query into SQL that works on your database. So, doing it in two steps and using ToList to evaluate inbetween overcomes that problem.

Linq get Date from DateTime nullable field

I have the following where I need to get only the Date (not datetime) from
ReqDate and RepDeclined which are both nullable datetime fields.
var info = from pr in db.Prog
join tf in db.In_Lens
on pr.PID equals tf.PID
select new
{ ReqDate = String.Format("{0:MM/dd/yyyy}",tf.ReqDate),
ReqDeclinedDate = tf.ReqDeclined.ToString("MM/dd/yyyy")
}).ToList()
It is not working as ReqDate and RepDeclined are both nullable datetime fields.
I also tried String.Format but no luck.
It says no overload for method.
You can try this, more elegant i think
var info = from pr in db.Prog
join tf in db.In_Lens
on pr.PID equals tf.PID
select new
{ ReqDate = !string.IsNullOrEmpty(tf.ReqDate) ? string.Format("{0:MM/dd/yyyy}",tf.ReqDate) : string.Empty(),
ReqDeclinedDate = !string.IsNullOrEmpty(tf.ReqDeclined) ? tf.ReqDeclined.ToString("MM/dd/yyyy") : string.Empty()
}).ToList()
I just way changed my answer.. basically.. you need to get back a couple datetimes in your new collection.. and then when you use those values, you can do the String.Format(). The reason is LINQ boils down to SQL, and there's no String.Format() converter (yet?).
so when you loop through the results, you can transform those results to display propertly (i.e. String.Format(...)).. but you will not be able to select out and convert the results in one linq statement, you might be able to do it LAMBDA (.ForEach()), which would be able to iterate through the results, however, it would just be a shorhtand way of doing what i described above..
...to the best of my knowledge

Linq to EF Expression Tree / Predicate int.Parse workaround

I have a linq Entity called Enquiry, which has a property: string DateSubmitted.
I'm writing an app where I need to return IQueryable for Enquiry that have a DateSubmitted within a particular date range.
Ideally I'd like to write something like
IQueryable<Enquiry> query = Context.EnquirySet.AsQueryable<Enquiry>();
int dateStart = int.Parse("20090729");
int dateEnd = int.Parse("20090930");
query = (from e in query
where(enq => int.Parse(enq.DateSubmitted) < dateEnd)
where(enq => int.Parse(enq.DateSubmitted) > dateStart)
select e);
Obviously Linq to EF doesn't recognise int.Parse, so I think I can achieve what I want with an Expression method that returns a predicate???
I've been playing around with PredicateBuilder and looking all over but I've successfully fried my brains trying to work this out. Sure I could add another property to my Entity and convert it there but I'd really like to understand this. Can anyone explain or give an example/link that doesn't fry my brains?
Thanks in advance
Mark
If you know your date strings are valid, and they're really in that order (which is a natural sort order) you might be able to get away with string comparisons:
IQueryable<Enquiry> query = Context.EnquirySet.AsQueryable<Enquiry>();
string dateStart ="20090729";
string dateEnd = "20090930";
query = (from e in query
where(enq => enq.DateSubmitted.CompareTo(dateEnd)) < 0)
where(enq => enq.DateSubmitted.CompareTo(dateStart)) > 0)
select e);

Resources