Golda
Golda

Reputation: 3891

LINQ Query to Convert string to datetime

I want to convert the string value to date time

Class

public class demoDate
{
    public DateTime DueDate;
    public int OrderReportID;

    public DateTime _DueDate 
    { 
        get { return DueDate; } 
        set { DueDate = value; } 
    }

    public int _OrderReportID 
    { 
        get { return OrderReportID; } 
        set { OrderReportID = value;} 
    }
}

Query

var DateQuery = (from o in db.Order_Reports
                 select new demoDate {
                    DueDate = System.DateTime.Parse(o.ReportDueDateTime), 
                    OrderReportID = o.OrderReportID
                 }).ToList();

This coding shows following error

LINQ to Entities does not recognize the method 'System.DateTime Parse(System.String)' method, and this method cannot be translated into a store expression.

Upvotes: 10

Views: 39759

Answers (3)

Halil
Halil

Reputation: 1

DateTime myDateTime = Convert.ToDateTime(DateTimePicker.Text);

var kayitVarmi = (from myfTable in db.tbl_myfTable 
                              .
                              .
                              .
                              .                      
                              where
                                tbl_donemAyYil.donemAyYilKu == myDateTime 

Upvotes: 0

Volodymyr Baydalka
Volodymyr Baydalka

Reputation: 3645

If you need convert it with SQL you can try use SqlFunctions.DateAdd and just add zero interval.

var DateQuery = db.Order_Reports.Select(o => new demoDate {
    DueDate = SqlFunctions.DateAdd("day", 0, o.ReportDueDateTime), 
    OrderReportID = o.OrderReportID
 });

Upvotes: 21

i3arnon
i3arnon

Reputation: 116636

You need to first materialize the query (i.e. load the data) to your application and then parse it. Entity Framework doesn't know how to execute .Net methods (like DateTime.Parse), it only knows how to translate them to SQL

var DateQuery = db.Order_Reports.ToList().Select(o => new demoDate 
{
    DueDate=DateTime.Parse(o.ReportDueDateTime),
    OrderReportID= o.OrderReportID
});

Upvotes: 6

Related Questions