我正在尝试进行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(带时间码),我试图仅根据日期进行解析。
答案 0 :(得分:5)
你不能简单地使用'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();
答案 1 :(得分:3)
这个甚至可以在日期字段中使用索引:
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();
答案 2 :(得分:0)
EF无法将Date
DateTime
部分转换为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();