I'm trying something similar to this:
我正在尝试类似的东西:
How to use scalar-valued function with linq to entity?
如何使用带有linq的标量值函数实体?
However I'm not using EDMX, but instead just DbContext and code first.
但是我没有使用EDMX,而是先使用DbContext和代码。
I've come across this:
我遇到过这个:
https://codefirstfunctions.codeplex.com/
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)
Where it will call a scalar function (LatLongDistanceCalc) on SQL Server.
它将在SQL Server上调用标量函数(LatLongDistanceCalc)。
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.
没有使用EDMX有没有办法做到这一点?我知道你可以构建一个手动查询,但这不会是优先的,因为我想带回具有延迟加载代理等的实体以及构建更复杂的查询。
1 个解决方案
#1
27
You should be able to use a scalar SQL function in your Where
criterias with CodeFirstStoreFunctions
您应该能够在CodeFirstStoreFunctions的Where标准中使用标量SQL函数
Assuming you want to map SQL function [dbo].[LatLongDistanceCalc], and according to the test suite:
假设您要映射SQL函数[dbo]。[LatLongDistanceCalc],并根据测试套件:
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();
}
}
usage would then be:
那么用法是:
context.Locations
.Where(e => MyDataContext.LatLongDistanceCalc(e.Lat, e.Long, lat, long) >= 10)
#1
27
You should be able to use a scalar SQL function in your Where
criterias with CodeFirstStoreFunctions
您应该能够在CodeFirstStoreFunctions的Where标准中使用标量SQL函数
Assuming you want to map SQL function [dbo].[LatLongDistanceCalc], and according to the test suite:
假设您要映射SQL函数[dbo]。[LatLongDistanceCalc],并根据测试套件:
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();
}
}
usage would then be:
那么用法是:
context.Locations
.Where(e => MyDataContext.LatLongDistanceCalc(e.Lat, e.Long, lat, long) >= 10)