您可以通过创建一些模型定义的函数来做到这一点。请参阅此链接: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)))