Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

c# - LINQ to Entities does not recognize the method 'System.DateTime ToDateTime(System.String)' method

I am trying to convert one application to EntityFrameWork codefirst. My present code is

 string sFrom  ="26/12/2013";
 select * FROM Trans where  CONVERT(datetime, Date, 105) >=   CONVERT(datetime,'" + sFrom + "',105) 

And i tried

 DateTime dtFrom = Convert.ToDateTime(sFrom );
TransRepository.Entities.Where(x  =>Convert.ToDateTime(x.Date) >= dtFrom) 

But I got an error like this

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

Please help Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

when you do this:

TransRepository.Entities.Where(x  =>Convert.ToDateTime(x.Date) >= dtFrom) 

LINQ to Entities cannot translate most .NET Date methods (including the casting you used) into SQL since there is no equivalent SQL. What you need to do is to do below:

 DateTime dtFrom = Convert.ToDateTime(sFrom );
  TransRepository
 .Entities.ToList()//forces execution
 .Where(x  =>Convert.ToDateTime(x.Date) >= dtFrom) 

but wait the above query will fetch entire data, and perform .Where on it, definitely you don't want that,

simple soultion would be this, personally, I would have made my Entity field as DateTime and db column as DateTime

but since, your db/Entity Date field is string, you don't have any other option, other than to change your field in the entity and db to DateTime and then do the comparison


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...