emc*_*cor -4 sql-server entity-framework c#
我有一个 SQL 服务器数据库,其中有一列名为“时间”的格式为“日期时间”。
在 C# 实体框架中,我想获取日期在今天上午 8 点之后的所有行:
using (var db = new intrabaseEntities())
{
var getQ = db.intrads.Where(s => s.Time.Value.TimeOfDay >= TimeSpan.Parse("8:00") & s.Time >= DateTime.Now.Date);
foreach (var x in getQ)
{
MessageBox.Show(x.ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
代码在编译器中没有显示错误,但抛出异常:
System.NotSupportedException {“LINQ to Entities 不支持指定的类型成员‘TimeOfDay’。仅支持初始值设定项、实体成员和实体导航属性。”}
如何让查询选择日期在今天上午 8 点之后的所有值?
此代码检索今天日期的行,但我还需要按今天上午 8 点之后的白天进行区分:
var getQ =
db.intrads.Where(s => DbFunctions.TruncateTime(s.Time) == DbFunctions.TruncateTime(DateTime.Today));
Run Code Online (Sandbox Code Playgroud)
您的答案可能如下所示:
// I don't know why you weren't using UTC time in your sample. That leaves you at the mercy
// of your server's time zone which is rarely a good policy. If you must though you can
// replace `UtcNow` with `Now`.
var getQ = db.intrads.Where(s => s.Time >= DateTime.UtcNow.Date.AddHours(8));
Run Code Online (Sandbox Code Playgroud)
我对实体框架一无所知,也不知道您的模型/架构是什么样的。根据我对 C# 和 LINQ 的一般知识,这只是在黑暗中的一个镜头。根据您提供的错误消息,我认为实体框架告诉您该TimeOfDay属性与您的数据库中的任何内容都不匹配。
最后看起来好像您的Time财产可以为空。如果您尝试使用空值运行它,那么您的原始查询将会失败。如果您必须从 a 中获取一个值,Nullable<T>那么检查 null 或使用该GetValueOrDefault()方法而不是Value.