【问题标题】:cast to decimal in linq query在 linq 查询中转换为十进制
【发布时间】:2021-08-27 11:31:13
【问题描述】:
var data = await dbContext.Set<OwnerData>().FromSqlRaw(@"
                SELECT [OWP].[OwnerProfileId],                    
                SELECT [OWP].[Email],
                FROM [user].[OwnerProfile] AS [OWP]
                CAST(ISNULL([OWB].[CustomBalance], 0) AS decimal(18, 3)) AS [CustomBalance]
                INNER JOIN [user].[OwnerBalance] AS [OWB] ON [OWB].[OwnerProfileId] = [OWP].[OwnerProfileId]
                WHERE [ThirdPartyRefId] = {0}", ownerProfileId)
               .ToListAsync();

我把它改写成这样的linq表达式

 var data = await _context.Set<OwnerProfile>()
                .Include(x => x.OwnerBalances)                
                .Where(x => x.ThirdPartyRefId== ownerProfileId)
                .ToListAsync();

不知道怎么设置

CAST(ISNULL([OWB].[CustomBalance], 0) AS decimal(18, 3)) AS [CustomBalance]

进入 lambda 查询

【问题讨论】:

  • 你的实体类的CustomBalance属性是什么类型的?为什么不坚持使用原始 SQL?
  • decimal in .NET 没有可配置的精度或比例

标签: c# .net linq


【解决方案1】:

如果没有类定义,很难给您具体说明,但您可以尝试添加如下内容:

var data = await _context.Set<OwnerProfile>()
                .Include(x => x.OwnerBalances)                
                .Where(x => x.ThirdPartyRefId== ownerProfileId)
                .Select(x => new 
                 {
                    x.Prop1,
                    x.Prop2,
                    CustomerBalance = x.CustomerBalance.Value != null ? x.CustomerBalance.Value : 0
                 })
                .ToListAsync();

您也可以将 select 语句移到查询之外:

var newData = data.Select(x => new 
              {
                 x.Prop1,
                 x.Prop2,
                 CustomerBalance = x.CustomerBalance.Value != null ? x.CustomerBalance.Value : 0
              })

您也许可以在第二个版本中使用条件访问,但在第一个版本中可能不行。

【讨论】:

    猜你喜欢
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 2017-11-07
    • 2012-08-11
    相关资源
    最近更新 更多