J86*_*J86 28 linq-to-entities entity-framework-4 c#-4.0 entity-functions
我正在使用Entity Framework Code First.使用LINQ to Entity我想根据DateTime值获取记录.这是我目前的代码:
/// <summary>
/// A method to check and see if the Parsed Game already exists on the
/// database. If Yes, then True is returned, otherwise False is returned.
/// </summary>
/// <param name="context">The Db Context to use</param>
/// <param name="homeTeam">The Name of the Home Team for the Game.</param>
/// <param name="awayTeam">The Name of the Away Team for the Game.</param>
/// <param name="date">The Date of the Game</param>
/// <returns></returns>
public bool doesGameAlreadyExist(PContext context, String homeTeam, String awayTeam, String date)
{
string dtObjFormat = "dd MMM yyyy";
DateTime dt;
DateTime.TryParseExact(date, dtObjFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
var result = context.Games.Where(x => EntityFunctions.TruncateTime(x.Start) == dt.Date).FirstOrDefault();
return result != null;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码抛出以下错误:
LINQ to Entities does not recognize the method 'System.Nullable`1[System.DateTime] TruncateTime(System.Nullable`1[System.DateTime])' method, and this method cannot be translated into a store expression.
Run Code Online (Sandbox Code Playgroud)
我也尝试了以下代码,我得到了同样的错误:
var result = context.Games.Where(x => EntityFunctions.TruncateTime(x.Start) == EntityFunctions.TruncateTime(dt.Date)).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
Emr*_*ain 68
我最近在将我的Web应用程序从Entity Framework 5升级到Entity Framework 6时遇到了这个问题.然后,我意识到System.Data.Entity需要从应用程序中完全删除DLL才能使用Entity Framework 6.实体框架6不属于.NET Framework,因此它独立于System.Data.Entity dll.为了截断时间,您需要使用System.Data.Entity.DbFunctions.TruncateTime(...)EntityFramework.dll中的方法.是的,这解决了我的问题.
结论:如果您使用的是Entity Framework 6,请首先删除引用System.Data.EntityDLL,然后在代码中替换EntityFunctions.TruncateTime(..)为System.Data.Entity.DbFunctions.TruncateTime(...).[来自EntityFramework.dll]
我没有删除的参考System.Data.Entity,我刚从改变了通话DbFunctions.TruncateTime,以System.Data.Entity.DbFunctions.TruncateTime它为我工作.
我正在使用实体6.