c# - Entity Framework 6 Code First 自定义函数

标签 c# linq entity-framework entity-framework-6

我正在尝试类似的东西:

How to use scalar-valued function with linq to entity?

但是我没有使用 EDMX,而是先使用 DbContext 和代码。

我遇到过这个:

https://codefirstfunctions.codeplex.com/

但是用法不合适。我想要实现的是能够做到这一点:

var locations = context.Locations.Where(e => Functions.LatLongDistanceCalc(e.Lat, e.Long, lat, long) >= 10)

它将调用 SQL Server 上的标量函数 (LatLongDistanceCalc)。

有没有不使用 EDMX 的方法来做到这一点?我知道您可以构建手动查询,但这不是首选,因为我想带回具有延迟加载代理等的实体以及构建更复杂的查询。

最佳答案

您应该能够在您的 Where 条件中使用 CodeFirstStoreFunctions 的标量 SQL 函数

假设您要映射 SQL 函数 [dbo].[LatLongDistanceCalc],并根据 the test suite :

public class MyDataContext: DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
       //...

       modelBuilder.Conventions.Add(new FunctionsConvention("dbo", this.GetType()));
    }

    // "CodeFirstDatabaseSchema" is a convention mandatory schema name
    // "LatLongDistanceCalc" is the name of your function

    [DbFunction("CodeFirstDatabaseSchema", "LatLongDistanceCalc")]
    public static int LatLongDistanceCalc(int fromLat, int fromLong,
                                                       int toLat, int toLong)
    {
       // no need to provide an implementation
       throw new NotSupportedException();
    }
}

用法将是:

context.Locations
       .Where(e => MyDataContext.LatLongDistanceCalc(e.Lat, e.Long, lat, long) >= 10)

关于c# - Entity Framework 6 Code First 自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29517627/

相关文章:

c# - 将数据库表映射到数据协定时如何避免创建其他类?

c# - 将 SQL 查询转换为 LINQ 查询

linq - LINQ 内部如何工作?

c# - 返回带有 Entity Framework 代码优先错误 : Unable to evaluate the expression. 操作不支持的子对象。未知错误:0x80070057

c# - 如何在C#中将JSON对象序列化或反序列化到一定深度?

c# - 执行左连接和多个内部连接时嵌套的替代方法

c# - 圈复杂度为 31,这是从哪里来的?

c# - 如何使用 Linq 查找 Min() 并将 Min 元素设置为 0

c# - 如何仅将实体的已更改属性更新到 Entity Framework

c# - Entity Framework -使用存储过程急于加载对象图