33

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;

}

上記のコードは、次のエラーをスローします。

    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.

次のコードも試しましたが、同じエラーが発生します。

var result = context.Games.Where(x => EntityFunctions.TruncateTime(x.Start) == EntityFunctions.TruncateTime(dt.Date)).FirstOrDefault();

私は何を間違っていますか?

4

3 に答える 3

8

参照を削除しませんでした。System.Data.Entity呼び出しを からDbFunctions.TruncateTimeに変更しただけで、うまくいきSystem.Data.Entity.DbFunctions.TruncateTimeました。

Entity6を使用しています。

于 2016-10-25T14:17:53.877 に答える
-1
DateTime? dt = DateTime.Parse(sText);
campaigns = _CampaignMasterRepository.Get().OrderByDescending(a => a.LaunchOn).Where(a => a.UserId == obj_User.ID && a.CampaignStatus == (int)OmevoEnums.CampaignStatus.Sent && a.CampaignName.Contains(sText) || DbFunctions.TruncateTime(a.LaunchOn) == DbFunctions.TruncateTime(dt)).ToList();

Linq クエリで日付の結果を取得するには、この関数を使用します。

于 2015-11-19T11:34:23.413 に答える