9

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

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)))

我正在使用实体框架代码优先。

当然,Linq 抱怨

LINQ to Entities 无法识别方法“System.Decimal Parse(System.String)”方法

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

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)
4

3 回答 3

10

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

具体来说,要添加一些函数将字符串转换为十进制和字符串转换为 int,请执行以下步骤:

以 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)))
于 2012-08-31T14:49:12.470 回答
0

不幸的是 LINQ to SQL 不能创建一个带有字符串到十进制转换的 SQL 表达式。

如果您想这样做,您必须使用以下命令执行您自己的查询:

执行存储查询

于 2012-08-31T13:21:59.307 回答
0

您可以将 转换string为,而不是将其转换为。如果其他人不这样做,这种方法可能会奏效。decimaldecimalstring

于 2012-08-31T13:24:11.660 回答