Entity Framework 6 个代码优先自定义函数
Entity Framework 6 Code First Custom Functions
我正在尝试类似的操作:
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 服务器上调用标量函数 (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)
我正在尝试类似的操作:
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 服务器上调用标量函数 (LatLongDistanceCalc) 的位置。
有没有不使用 EDMX 的方法?我知道您可以构建一个手动查询,但这不是首选,因为我想带回具有延迟加载代理等的实体以及构建更复杂的查询。
您应该能够在 Where
条件中使用 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)