gpt4 book ai didi

c# - 在组连接 linq 查询中将字符串转换为十进制

转载 作者:太空狗 更新时间:2023-10-29 17:48:25 26 4
gpt4 key购买 nike

我必须连接两个表,但只返回第二个表中的那些记录,其中与第一个表中的记录关联的所有记录的“值”总和相同。

from p in db.TPs
join n in db.TNs
on p.Key equals n.Key
where (decimal.Parse(p.Value) == db.TNs.Where( nn => nn.Key == p.Key )
.Sum( nn=> decimal.Parse(kk.Value)))

我正在使用 Entity Framework Code-First。

当然,Linq 会提示

LINQ to Entities does not recognize the method 'System.Decimal Parse(System.String)' method

表很大,我必须减少输出,所以在客户端进行这种转换是不可能的。列类型转换也不是一种选择。

SQL 查询是:

select * from TP as p
join * from TN as n on n.Key = p.Key
where p.Value = (select sum(cast(n.Value as decimal(12,2))) from TN where Key = p.Key)

最佳答案

您可以通过创建一些模型定义的函数来做到这一点。请参阅此链接:Creating and Calling Model-Defined Functions in at least Entity Framework 4

具体来说,要添加一些将字符串转换为十进制和将字符串转换为整数的函数,请按照以下步骤操作:

以 XML 格式打开您的 .EDMX 文件,以便您可以编辑文本。

将您的自定义转换函数添加到“CSDL 内容”部分的“方案”部分

<edmx:ConceptualModels>
<Schema....>

新功能:

<Function Name="ConvertToInt32" ReturnType="Edm.Int32">
<Parameter Name="myStr" Type="Edm.String" />
<DefiningExpression>
CAST(myStr AS Edm.Int32)
</DefiningExpression>
</Function>
<Function Name="ConvertToDecimal" ReturnType="Edm.Decimal">
<Parameter Name="myStr" Type="Edm.String" />
<DefiningExpression>
CAST(myStr AS Edm.Decimal(12, 2))
</DefiningExpression>
</Function>

(修改上述 Edm.Decimal 的精度以满足您的需要。)

然后,在您的 C# 代码中,您需要创建可以存储在静态类中的相应静态方法:

// NOTE: Change the "EFTestDBModel" namespace to the name of your model
[System.Data.Objects.DataClasses.EdmFunction("EFTestDBModel", "ConvertToInt32")]
public static int ConvertToInt32(string myStr)
{
throw new NotSupportedException("Direct calls are not supported.");
}

// NOTE: Change the "EFTestDBModel" namespace to the name of your model
[System.Data.Objects.DataClasses.EdmFunction("EFTestDBModel", "ConvertToDecimal")]
public static decimal ConvertToDecimal(string myStr)
{
throw new NotSupportedException("Direct calls are not supported.");
}

最后,调用您的新方法:

using (var ctx = new EFTestDBEntities())
{
var results = from x in ctx.MyTables
let TheTotal = ctx.MyTables.Sum(y => ConvertToDecimal(y.Price))
select new
{
ID = x.ID,
// the following three values are stored as strings in DB
Price = ConvertToDecimal(x.Price),
Quantity = ConvertToInt32(x.Quantity),
Amount = x.Amount,
TheTotal
};
}

您的具体示例如下所示:

from p in db.TPs
join n in db.TNs
on p.Key equals n.Key
where (ConvertToDecimal(p.Value) ==
db.TNs.Where( nn => nn.Key == p.Key ).Sum( nn=> ConvertToDecimal(kk.Value)))

关于c# - 在组连接 linq 查询中将字符串转换为十进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12216043/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com