GetTodayItemCount()尝试使用Items模型中的CreatedDtt获取今天的物品计数.由于CreatedDtt是可空的Datetime(DateTime?),因此我在Where的lambda表达式中使用三元运算符来确保以后在相等比较中不尝试访问空值的日期.
但是,我仍然得到经典的NullReferenceException吗?对象引用未设置为对象错误的实例,我可以确认问题所在在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?如何在不出现NullReferenceException错误的情况下完成GetTodayItemCount()的预期结果?
由于该解决方案似乎并不像我预期的那么简单,因此我在下面添加了堆栈跟踪,以防其中有任何用途:
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]
解决方法:
您不能将C#逻辑应用于RDBMS Server列.如果要测试日期等模糊精度数据类型,则应改用范围,例如:
.Where(row => row.CreatedDtt != null &&
row.CreatedDtt >= DateTime.Now.Date &&
row.CreatedDtt < DateTime.Now.Date.AddDays(1)));