Entity Framework 6 Code First 自定义函数 [英] Entity Framework 6 Code First Custom Functions
问题描述
我正在尝试类似的方法:
I'm trying something similar to this:
但是我没有使用 EDMX,而是首先使用 DbContext 和代码.
However I'm not using EDMX, but instead just DbContext and code first.
我遇到过这个:
https://codefirstfunctions.codeplex.com/
但用法不合适.我想要实现的是能够做到这一点:
But the usage isn't suitable. What I am trying to achieve is to be able to do this:
var locations = context.Locations.Where(e => Functions.LatLongDistanceCalc(e.Lat, e.Long, lat, long) >= 10)
它将在 SQL Server 上调用标量函数 (LatLongDistanceCalc) 的位置.
Where it will call a scalar function (LatLongDistanceCalc) on SQL Server.
有没有不使用 EDMX 的方法来做到这一点?我知道您可以构建手动查询,但这不是首选,因为我想使用延迟加载代理等返回实体以及构建更复杂的查询.
Is there any way to do this without using EDMX? I know that you can construct a manual query but this wouldn't be prefereable because I want to bring back entities with lazy loading proxies etc as well as building up a more complex query.
推荐答案
您应该能够在带有 CodeFirstStoreFunctions
You should be able to use a scalar SQL function in your Where
criterias with CodeFirstStoreFunctions
假设你想映射 SQL 函数 [dbo].[LatLongDistanceCalc],并根据 测试套件:
Assuming you want to map SQL function [dbo].[LatLongDistanceCalc], and according to 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)
这篇关于Entity Framework 6 Code First 自定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!