GetTodayItemCount()
尝试使用CreatedDtt
模型中的Items
获取今天的商品计数。由于CreatedDtt
是可空的日期时间(DateTime?
),因此我在Where
的lambda表达式中使用三元运算符来确保以后不尝试访问空值的日期在我的平等比较中。
但是,我仍然遇到典型的NullReferenceException? Object reference not set to an instance of an object
错误,并且可以确认问题所在。{p> 1。
row.CreatedDtt.Value.Date
在预先检查 public Int64 GetTodayItemCount()
{
OrmLiteConnectionFactory dbFactory = new OrmLiteConnectionFactory(dbConn, SqlServerDialect.Provider);
using (IDbConnection db = dbFactory.Open())
{
SqlExpression<Items> itemMatch = db.From<Items>()
.Where(row =>
(row.CreatedDtt.HasValue ?
row.CreatedDtt.Value.Date : DateTime.MinValue) == DateTime.Today
);
Int64 itemCount = db.Count(itemMatch);
db.Close();
return itemCount;
}
}
的有效值时如何访问row.CreatedDtt.Value.Date
?如何在没有出现GetTodayItemCount()
错误的情况下完成NullReferenceException
的预期结果?
由于该解决方案似乎不像我预期的那么简单,因此我在下面添加了堆栈跟踪,以防其中有任何用途:
at ServiceStack.OrmLite.SqlExpression`1.GetQuotedColumnName(ModelDefinition tableDef, String memberName)
at ServiceStack.OrmLite.SqlExpression`1.GetMemberExpression(MemberExpression m)
at ServiceStack.OrmLite.SqlExpression`1.VisitMemberAccess(MemberExpression m)
at ServiceStack.OrmLite.SqlExpression`1.Visit(Expression exp)
at ServiceStack.OrmLite.SqlExpression`1.VisitBinary(BinaryExpression b)
at ServiceStack.OrmLite.SqlExpression`1.Visit(Expression exp)
at ServiceStack.OrmLite.SqlExpression`1.VisitBinary(BinaryExpression b)
at ServiceStack.OrmLite.SqlExpression`1.Visit(Expression exp)
at ServiceStack.OrmLite.SqlExpression`1.VisitLambda(LambdaExpression lambda)
at ServiceStack.OrmLite.SqlExpression`1.Visit(Expression exp)
at ServiceStack.OrmLite.SqlExpression`1.AppendToWhere(String condition, Expression predicate)
at ServiceStack.OrmLite.SqlExpression`1.Where(Expression`1 predicate)
at GroupRedemptionsScanner.DBHandlers.GetTodayItemCount() in [directory/file/line number etc]
答案 0 :(得分:3)
您不能将C#逻辑应用于RDBMS Server列。如果要测试日期等模糊精度数据类型,则应改用范围,例如:
.Where(row => row.CreatedDtt != null &&
row.CreatedDtt >= DateTime.Now.Date &&
row.CreatedDtt < DateTime.Now.Date.AddDays(1)));
答案 1 :(得分:0)
我试图以您可以想象的所有方式来再现您的错误,但我无法。唯一的方法是显式地将行保留为空。但我不知道是否可能。无论如何,我建议您使用Null传播对其进行重构。这样:
.Where(row => row?.CreatedDtt?.Date == DateTime.Today);