繁体   English   中英

实体框架日期解析

[英]Entity Framework Date Parsing

我正在尝试进行LINQ to Entities查询(我仍然非常熟悉EF并且我正在学习它比LinqToSQL差异化)并且我正在尝试做这样的事情:

DateTime begin = new DateTime(2011, 1, 1);

Apps = (from app in context.Instances
                 where app.ReleaseDate.Date == begin
                 select new ScalpApp
                 {
                 Image = app.Image,
                 PublisherName = app.PublisherName,
                 }).ToList();

虽然这在LinqPad中有效,但它不在我的代码中。 抛出的异常是:

 The specified type member 'Date' is not supported in LINQ to Entities. 

仅支持初始值设定项,实体成员和实体导航属性。

我如何在LinqToEF中执行此操作? DB中的字段是完整的DateTime(带有时间码),我试图仅根据日期进行解析。

你不能简单地使用'app.ReleaseDate.Data',但你可以:

var begin = new DateTime(2011, 1, 1);
var end = begin.AddHours(24);

Apps = (from app in context.Instances
             where 
               (app.ReleaseDate >= begin) and
               (app.ReleaseDate < end)
             select new ScalpApp
             {
             Image = app.Image,
             PublisherName = app.PublisherName,
             }).ToList();

这个甚至可以在日期字段上使用索引:

DateTime begin = new DateTime(2011, 1, 1);
DateTime end = new DateTime(2011, 1, 2);

Apps = (from app in context.Instances
             where 
               (app.ReleaseDate >= begin) and
               (app.ReleaseDate < end)
             select new ScalpApp
             {
             Image = app.Image,
             PublisherName = app.PublisherName,
             }).ToList();

EF无法将DateTime Date部分转换为SQL代码。 但它有EntityFunctions.TruncateTime方法,可以转换为规范的TruncateTime函数:

DateTime begin = new DateTime(2011, 1, 1);

Apps = (from app in context.Instances
        where EntityFunctions.TruncateTime(app.ReleaseDate) == begin
        select new ScalpApp {
            Image = app.Image,
            PublisherName = app.PublisherName,
        }).ToList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM