C# 使用WHERE子句获取可为null的列的和
使用C# 使用WHERE子句获取可为null的列的和,c#,sql,sql-server,entity-framework-6,C#,Sql,Sql Server,Entity Framework 6,使用WHERE子句检索EF6中某列的SUM时遇到一些问题 我用的是: double oh2 = raptorEntities.OnlineHistories .Where(us => us.Id == user.Id) .Sum(r => (double?) r.SessionTime) ?? 0; // Need the cast as we may get a null ! 其思想是在OnlineHistories中获取SessionTime列的和,其中User
WHERE
子句检索EF6中某列的SUM
时遇到一些问题
我用的是:
double oh2 = raptorEntities.OnlineHistories
.Where(us => us.Id == user.Id)
.Sum(r => (double?) r.SessionTime) ?? 0; // Need the cast as we may get a null !
其思想是在OnlineHistories中获取SessionTime列的和,其中
Userid=x
现在SessionTime列是一个计算列,包含值。。。并且允许NULL
有人能修复这个表达式使它工作吗
更新一个
使用建议的修复程序:
double oh2 = raptorEntities.OnlineHistories.Where(us => us.Id == user.Id &&
us.SessionTime.HasValue).Sum(r => r.SessionTime);
我必须像这样投射它,然后收到一个错误:
double oh2 = raptorEntities.OnlineHistories.Where(us => us.Id == user.Id &&
us.SessionTime.HasValue).Sum(r => (double)r.SessionTime);
错误2019:指定的成员映射无效。类型
中成员“SessionTime”的“Edm.Double[Nullable=True,DefaultValue=]”
类型“RaptorModel.OnlineHistory”与不兼容
'SqlServer.int[Nullable=True,DefaultValue=,StoreGeneratedPattern=Computed]'
类型中成员“SessionTime”的
“RaptorModel.Store.OnlineHistory”。RaptorDb C:\Users\Dave\documents\visual
studio 2015\Projects\RaptorService\RaptorDb\RaptorModels.edmx 835
映射如下所示:
<EntitySetMapping Name="OnlineHistories">
<EntityTypeMapping TypeName="RaptorModel.OnlineHistory">
<MappingFragment StoreEntitySet="OnlineHistory">
<ScalarProperty Name="SessionTime" ColumnName="SessionTime" />
<ScalarProperty Name="Id" ColumnName="Id" />
<ScalarProperty Name="UserId" ColumnName="UserId" />
<ScalarProperty Name="OnlineAt" ColumnName="OnlineAt" />
<ScalarProperty Name="OfflineAt" ColumnName="OfflineAt" />
</MappingFragment>
</EntityTypeMapping>
更新二:
SessionTime没有类型:
只需过滤掉这些行:
double oh2 = raptorEntities.OnlineHistories
.Where(us => us.Id == user.Id && us.SessionTime.HasValue)
.Sum(r => r.SessionTime);
编辑:
您正在查看edmx:Mappings
。而是在edmx:StorageModels
中查找类型。同样在sqlserver
的objectexplorer
中展开表格->联机历史->列
,您可能会看到类型是int
。在您的模型中,它的类型是double
。如果在edmx
中手动将列类型从int
更改为double
,则可以重现此错误。但在我的模型中,默认情况下它被创建为int
。您可以尝试从模型中删除该表,然后再次导入它
注意Sum
函数似乎消除了NULL
s本身:
double oh2 = raptorEntities.OnlineHistories
.Where(us => us.Id == user.Id)
.Sum(r => r.SessionTime);
为什么不过滤掉空值呢
double oh2 =
raptorEntities
.OnlineHistories
.Where(us => us.Id == user.Id && us.SessionTime != null)
.Sum(r => (double)r.SessionTime);
由于您希望将空值合并为零,因此忽略它们不会影响总和。@DaveGordon,SessionTime的类型是什么?SessionTime没有类型!我添加了图片来显示表和属性。@DaveGordon,应该有类型。您正在查看edmx:Mappings
。而是在edmx:StorageModels
中查找类型。同样,在Sql Server的对象资源管理器中展开tables->OnlineHistories->Columns,您可能会看到类型是int
。不知怎的,在你的模型中,它是双重类型的。如果在edmx
中手动将列类型从int
更改为double
,则可以重现此错误。但在我的模型中,默认情况下它被创建为int
。您可以从模型中删除该表,然后再次导入并重试吗?Nakerui将您的注释添加到您的答案中,我会将其标记为正确。还有一个逻辑错误,我是在比较列的Id,而不是用户Id。。。但这也是经过排序的。看起来您应该在edmx设计器中将类型更改为int?
。