简体   繁体   English

转换为值类型“Int32”失败,因为物化值为 null

[英]The cast to value type 'Int32' failed because the materialized value is null

I have the following code.我有以下代码。 I'm getting error:我收到错误:

"The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type." “转换为值类型‘Int32’失败,因为物化值为 null。结果类型的通用参数或查询必须使用可空类型。”

when CreditHistory table has no records.当 CreditHistory 表没有记录时。

var creditsSum = (from u in context.User
                  join ch in context.CreditHistory on u.ID equals ch.UserID                                        
                  where u.ID == userID
                  select ch.Amount).Sum();

How can I modify the query to accept null values?如何修改查询以接受 null 值?

A linq-to-sql query isn't executed as code, but rather translated into SQL. linq-to-sql 查询不作为代码执行,而是转换为 SQL。 Sometimes this is a "leaky abstraction" that yields unexpected behaviour.有时这是一个“泄漏的抽象”,会产生意想不到的行为。

One such case is null handling, where there can be unexpected nulls in different places.一种这样的情况是空处理,在不同的地方可能会出现意外的空值。 ...DefaultIfEmpty(0).Sum(0) can help in this (quite simple) case, where there might be no elements and sql's SUM returns null whereas c# expect 0. ...DefaultIfEmpty(0).Sum(0)在这种(非常简单)的情况下可以提供帮助,其中可能没有元素并且 sql 的SUM返回null而 c# 期望为 0。

A more general approach is to use ??更通用的方法是使用?? which will be translated to COALESCE whenever there is a risk that the generated SQL returns an unexpected null:只要有生成的 SQL 返回意外空值的风险,它就会被转换为COALESCE

var creditsSum = (from u in context.User
              join ch in context.CreditHistory on u.ID equals ch.UserID                                        
              where u.ID == userID
              select (int?)ch.Amount).Sum() ?? 0;

This first casts to int?这首先转换为int? to tell the C# compiler that this expression can indeed return null , even though Sum() returns an int .告诉 C# 编译器这个表达式确实可以返回null ,即使Sum()返回一个int Then we use the normal ??那我们用正常的?? operator to handle the null case.运算符来处理null情况。

Based on this answer, I wrote a blog post with details for both LINQ to SQL and LINQ to Entities.基于这个答案,我写了一篇博文,详细介绍了 LINQ to SQL 和 LINQ to Entities。

To allow a nullable Amount field, just use the null coalescing operator to convert nulls to 0.要允许可为空的Amount字段,只需使用空合并运算符将空值转换为 0。

var creditsSum = (from u in context.User
              join ch in context.CreditHistory on u.ID equals ch.UserID                                        
              where u.ID == userID
              select ch.Amount ?? 0).Sum();

I have used this code and it responds correctly, only the output value is nullable.我使用了这段代码并且它正确响应,只有输出值可以为空。

var packesCount = await botContext.Sales.Where(s => s.CustomerId == cust.CustomerId && s.Validated)
                                .SumAsync(s => (int?)s.PackesCount);
                            if(packesCount != null)
                            {
                                // your code
                            }
                            else
                            {
                                // your code
                            }

Had this error message when I was trying to select from a view.当我尝试从视图中进行选择时出现此错误消息。

The problem was the view recently had gained some new null rows (in SubscriberId column), and it had not been updated in EDMX (EF database first).问题是该视图最近获得了一些新的空行(在 SubscriberId 列中),并且尚未在 EDMX 中更新(首先是 EF 数据库)。

The column had to be Nullable type for it to work.该列必须是 Nullable 类型才能工作。

var dealer = Context.Dealers.Where(x => x.dealerCode == dealerCode).FirstOrDefault(); var Dealer = Context.Dealers.Where(x => x.dealerCode == DealerCode).FirstOrDefault();

Before view refresh:视图刷新前:

public int SubscriberId { get; set; }

After view refresh:视图刷新后:

public Nullable<int> SubscriberId { get; set; }

Deleting and adding the view back in EDMX worked.在 EDMX 中删除和添加视图有效。

Hope it helps someone.希望它可以帮助某人。

您正在使用aggregate函数,它没有让项目执行操作,您必须验证 linq 查询是否给出了一些结果,如下所示:

var maxOrderLevel =sdv.Any()? sdv.Max(s => s.nOrderLevel):0

I see that this question is already answered.我看到这个问题已经回答了。 But if you want it to be split into two statements, following may be considered.但是如果你想把它分成两个语句,可以考虑以下。

var credits = from u in context.User
              join ch in context.CreditHistory 
                  on u.ID equals ch.UserID                                        
              where u.ID == userID
              select ch;

var creditSum= credits.Sum(x => (int?)x.Amount) ?? 0;

Got this error in Entity Framework 6 with this code at runtime:在运行时使用以下代码在实体框架 6 中出现此错误:

var fileEventsSum = db.ImportInformations.Sum(x => x.FileEvents)

Update from LeandroSoares:莱安德罗苏亚雷斯的更新:

Use this for single execution:将此用于单次执行:

var fileEventsSum = db.ImportInformations.Sum(x => (int?)x.FileEvents) ?? 0

Original:原来的:

Changed to this and then it worked:改为这个然后它起作用了:

var fileEventsSum = db.ImportInformations.Any() ? db.ImportInformations.Sum(x => x.FileEvents) : 0;

I was also facing the same problem and solved through making column as nullable using "?"我也面临同样的问题,并通过使用“?”将列设置为可空来解决。 operator.操作员。

Sequnce = db.mstquestionbanks.Where(x => x.IsDeleted == false && x.OrignalFormID == OriginalFormIDint).Select(x=><b>(int?)x.Sequence</b>).Max().ToString();

Sometimes null is returned.有时会返回 null。

您的变量之一不可为空,但它正在尝试获取空值。您必须将该变量指定为 Ex:Nullable

"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Linq错误:强制转换为值类型&#39;Int32&#39;,因为物化值为null - Linq error: The cast to value type 'Int32' failed because the materialized value is null 转换为值类型“Int32”失败,因为通过加载网格视图实现的值为空 - The cast to value type 'Int32' failed because the materialized value is null via loading Grid View 转换为值类型&#39;int32&#39;失败,因为实例化值为null - Cast to value type 'int32' failed because the materialized value is null 转换为值类型“Int32”失败,因为实现值为null - The cast to value type 'Int32' failed because the materialized value is null 强制转换为值类型&#39;System.Int32&#39;,因为实例化值为null。 - The cast to value type 'System.Int32' failed because the materialized value is null. LINQ:转换为值类型&#39;System.Int32&#39;失败,因为具体化值为null - LINQ: The cast to value type 'System.Int32' failed because the materialized value is null 完全外连接:由于物化值为空,因此转换为值类型“System.Int32”失败 - Full outer join: The cast to value type 'System.Int32' failed because the materialized value is null 转换为值类型&#39;System.Int32&#39;失败,因为实例化值为null - The cast to value type 'System.Int32' failed because the materialized value is null 错误:强制转换为值类型&#39;System.Int32&#39;的原因是物化值为null - Error: The cast to value type 'System.Int32' failed because the materialized value is null 转换为值类型&#39;Int32&#39;失败空值LINQ - The cast to value type 'Int32' failed null value LINQ
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM