DevT
DevT

Reputation: 1511

LINQ to Entities does not recognize the method ToDateTime(System.String)

I have to use a "convert to datetime" method to compare the datetime with the reference month and year, as below

var res =  db.Table1
//other tables, and where conditions
.Select(x => new MyObj
{
      //...
      Imp = x.MyTable.FirstOrDefault(y => y.date_val >= System.Data.Entity.DbFunctions.AddMonths(Convert.ToDateTime("01/" + x.month + "/" + x.year), 1))).Description
})

I know that Convert.ToDateTime can't be translated in sql from the provider, I need an idea to do that query.

UPDATE: I wouldn't materialize the query before the Convert, because that obviously means takes all the records.

Upvotes: 4

Views: 2701

Answers (2)

DevT
DevT

Reputation: 1511

I Think I found the way to do it

var res =  db.Table1
//other tables, and where conditions
.Select(x => new MyObj
{
      //...
      Imp = x.MyTable.FirstOrDefault(y => y.date_val >= System.Data.Entity.DbFunctions.AddMonths(System.Data.Entity.DbFunctions.CreateDateTime(x.year, x.month, 1, 0, 0, 0), 1)).Description
})

Upvotes: 5

James Dev
James Dev

Reputation: 3009

It's a little crude but you can materialise the SQL query to list before you parse the date:

var res = db.Table1.ToList()
//other tables, and where conditions
.Select(x => new MyObj
{
//...
    Imp = x.MyTable.FirstOrDefault(y => y.date_val >= System.Data.Entity.DbFunctions.AddMonths(DateTime.Parse("01/" + x.month + "/" + x.year))).Description
})

Upvotes: 1

Related Questions