实体框架6 code首先自定义功能 [英] Entity Framework 6 Code First Custom Functions
问题描述
我想类似这样的:
<一个href=\"http://stackoverflow.com/questions/12481868/how-to-use-scalar-valued-function-with-linq-to-entity\">How使用标量值函数使用LINQ到实体?
不过我不使用EDMX,而只是和的DbContext code第一。
However I'm not using EDMX, but instead just DbContext and code first.
我遇到这样的:
的https://$c$cfirstfunctions.$c$cplex.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)
在哪里它会调用一个标量函数(LatLongDistanceCalc)SQL Server上。
Where it will call a scalar function (LatLongDistanceCalc) on SQL Server.
有没有办法做到这一点,而无需使用EDMX?我知道,你可以建立一个手动查询,但因为我要带回实体延迟加载代理等,以及建立一个更复杂的查询,这将不会是prefereable。
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.
推荐答案
您应该能够在你的其中,
审核规定使用一个标量SQL函数的 codeFirstStoreFunctions
You should be able to use a scalar SQL function in your Where
criterias with CodeFirstStoreFunctions
假设要映射的SQL函数[DBO]。[LatLongDistanceCalc],并且根据<一href=\"https://$c$cfirstfunctions.$c$cplex.com/SourceControl/latest#$c$cFirstStoreFunctionsSamples/ScalarFunctionSample.cs\"相对=nofollow>测试套件:
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)
这篇关于实体框架6 code首先自定义功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!