The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
在 EF 查询数据库时发生:
var list = db.TableA.Select(a => new { a.Id, bSum = a.TableB.Sum(b => b.Num), }).ToList();
本例中 TableB 有外键关联到 TableA.Id,TableB.Num 为 int,而非 int?。
原因是 EF 以为 Sum 的结果可能为 Nullable<int>,将代码修改如下即可正常:
var list = db.TableA.Select(a => new { a.Id, bSum = (int?)a.TableB.Sum(b => b.Num) ?? 0, }).ToList();
roll-back-to-mysql-connector-net-8-0-19
The-view-was-not-found
FromSqlRaw
csharp-substring
network-printer