在LinqPad中执行查询时出现异常
var allNewsInADay= (from t in Tnews where t.SendTime.Value.Year==2012 &&
t.SendTime.Value.Month==8 && t.SendTime.Value.Day==20 select t);
allNewsInADay.Dump();
例外:不支持成员访问'System.DateTime Value'
如果使用.HasValue属性:NotSupportedException: The member access 'Boolean HasValue' is not supported
- 我使用MySql 我的目的是获取特定日期的所有记录。
答案 0 :(得分:4)
您可以使用SqlFunctions.DatePart代替
用法:
where SqlFunctions.DatePart(t.SendTime, "yy") == 2012 &&
SqlFunctions.DatePart(t.SendTime, "mm") == 8 &&
SqlFunctions.DatePart(t.SendTime, "dd") == 20)
或
var dt = new DateTime(2012, 8, 20);
...
where t.SendTime == dt
或canonical functions(由所有提供商支持)
where EntityFunctions.Year(t.SendTime) == 2012
也许是空检查
t.SendTime != null
(或t.SendTime.HasValue
)作为第一个谓词
是必要的
或只是删除Value
!
答案 1 :(得分:0)
var rslt= (from t in Tnews
where t.SendTime.HasValue
&& t.SendTime.Value.Year==2012
&& t.SendTime.Value.Month==8
&& t.SendTime.Value.Day==20
select t);
或
var someDate = new DateTime(2012,8,20);
var rslt= (from t in Tnews
where t.SendTime.HasValue
&& t.SendTime.Value.Date==someDate
select t);
会有帮助吗?
upd:你做得不好。跑了这个:
class Program
{
public class TNews
{
public DateTime? SendTime { get; set; }
public string Id;
}
static void Main(string[] args)
{
var tnews = new TNews[]
{
new TNews { SendTime = new DateTime(2012,8,20), Id="2012-08-20" },
new TNews { SendTime = new DateTime(2012,8,20,12,20,0), Id="2012-08-20 12:20" },
new TNews { SendTime = new DateTime(2012,8,21), Id="2012-08-21" },
new TNews { SendTime = null, Id="null" },
};
var someDate = new DateTime(2012, 8, 20);
var rslt = (from t in tnews
where t.SendTime.HasValue
&& t.SendTime.Value.Date == someDate
select t);
foreach (var t in rslt)
{
Console.WriteLine(t.Id);
}
}
}
输出是:
2012-08-20
2012-08-20 12:20
Press any key to continue . . .