如何使用自定义 DbFunction 将字符串转换为小数

Plu*_*luc 3 c# linq entity-framework entity-framework-6

我有一个小数(和其他类型)保存为字符串的表格。我想在数据库上下文上编写一个 Linq 查询,该查询将转换为数据库转换而不是本地转换(出于性能原因)。

这个非工作示例在概念上是我想要实现的。

using ( var context = new MyContext() )
{
    return context.SomeTable
        .Select(o => new { o.Id, (decimal)o.SomeString });
}
Run Code Online (Sandbox Code Playgroud)

这是实现它的糟糕方法,因为它将在应用程序端运行转换。

using ( var context = new MyContext() )
{
    return context.SomeTable
        .Select(o => new { o.Id, o.SomeString })
        .ToList()
        .Select(o => new { o.Id, Convert.ToDecimal(o.SomeString) });
}
Run Code Online (Sandbox Code Playgroud)

我相信要走的路是使用 DbFunctions,但我找不到将它与 Code First 结合使用的方法。

这是部分答案,但我无法找到完成我定义此函数在 SQL 服务器上的作用的部分所需的文档。

[DbFunction("MyContext", "ConvertToDecimal")]
public static decimal ConvertToDecimal(string s)
{
    throw new Exception("Direct calls are not supported.");
}
Run Code Online (Sandbox Code Playgroud)

.

using ( var context = new MyContext() )
{
    return context.SomeTable
        .Select(o => new { o.Id, ConvertToDecimal(o.SomeString) });
}
Run Code Online (Sandbox Code Playgroud)

如果我使用的是 Edmx驱动的替代方案,这将是缺失的部分:

<Function Name="ConvertToDecimal" ReturnType="Edm.Decimal">
    <Parameter Name="s" Type="Edm.String" />
    <DefiningExpression>
        CAST(s AS decimal(22,6))
    </DefiningExpression>
</Function>
Run Code Online (Sandbox Code Playgroud)

我正在使用 Entity Framework 6 Code First。

Plu*_*luc 5

我找到了来自这个主题的一些信息的解决方案。

就像我在最初的问题中假设的那样,我把前两个部分放下了。最后一部分是在 DbModel 中注册您想要访问的函数以及如何使用它们。有不止一种方法可以做到这一点,但我使用了约定

public class MyFunctionsConvetion : IStoreModelConvention<EntityContainer>
{
    public void Apply(EntityContainer item, DbModel model)
    {
        //Get the Edm Model from the DbModel
        EdmModel storeModel = model.GetStoreModel();

        //Delare your parameters name, edm type and mode (You can ignore this if you use a parameter-less function)
        List<FunctionParameter> Parameters = new List<FunctionParameter>();
        Parameters.Add(FunctionParameter.Create("StringValue", GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In));

        //Same thing goes for the return type(s) (Why is it a list? Perhaps you can return tables? I haven't tested however since it is no use to me)
        List<FunctionParameter> ReturnParameters = new List<FunctionParameter>();
        ReturnParameters.Add(FunctionParameter.Create("ReturnValue", GetStorePrimitiveType(model, PrimitiveTypeKind.Decimal), ParameterMode.ReturnValue));

        //Create the payload and fill the required information alone with the parameter lists we declared
        EdmFunctionPayload payload = new EdmFunctionPayload();
        payload.IsComposable = true;
        payload.Schema = "dbo";
        payload.StoreFunctionName = "ConvertToDecimal";
        payload.ReturnParameters = ReturnParameters;
        payload.Parameters = Parameters;

        //Create the function with it's payload
        EdmFunction function = EdmFunction.Create("ConvertToDecimal", "MyContext", DataSpace.SSpace, payload, new MetadataProperty[] { });

        //Add it to the model
        storeModel.AddItem(function);
    }

    //Little helper method to get the primitive type based on the database provider
    private EdmType GetStorePrimitiveType(DbModel model, PrimitiveTypeKind typeKind)
    {
        return model
            .ProviderManifest
            .GetStoreType(TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(typeKind)))
            .EdmType;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我们在 OnModelCreating 方法中将约定添加到模型中

modelBuilder.Conventions.Add<MyProject.MyConventions.MyFunctionsConvention>();
Run Code Online (Sandbox Code Playgroud)

注意:代码可以更简洁,并以 DRY 的方式编写,但为了简单起见,我想像这样发布它,让您按照自己的意愿组织它。