【问题标题】:Entity Framework 6 Code First Custom FunctionsEntity Framework 6 Code First 自定义函数
【发布时间】:2015-04-08 14:31:06
【问题描述】:

我正在尝试类似的事情:

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 的情况下做到这一点?我知道您可以构建手动查询,但这并不可取,因为我想通过延迟加载代理等恢复实体,并构建更复杂的查询。

【问题讨论】:

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


    【解决方案1】:

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

    假设你要映射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)
    

    【讨论】:

    • 我不知道我怎么没早点得到这个,但这 100% 有效。谢谢你!
    • 我想补充一点,如果您在选择/上下文中,这将有效。如果你在它之外 - 它不会起作用。
    • 我一直在尝试将它与我创建的 Max 函数一起使用,没有输入参数,到目前为止还没有成功。我总是得到 NotSupportedException。
    • @yopez83 你应该发布一个问题,详细说明你的问题,以便有人可以帮助你
    • 我有一个问题,这个答案不支持这种情况。像这样的sql:select id, dbo.fnDecrypt(seller, 'key123') as Seller from table where dbo.fnDecrypt(seller, 'key123') like '%seller name%', fnDecrypt的第一个参数是varbinary(max ),是使用sql server EncryptByPassPhrase算法得到的结果,类的seller属性是字符串。
    猜你喜欢
    • 1970-01-01
    • 2013-05-20
    • 2016-01-30
    • 1970-01-01
    • 2013-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多