我可以覆盖Entity Framework查询生成器吗?

时间:2015-02-27 12:56:59

标签: c# entity-framework gis geospatial

实体框架上下文正在为我生成查询。

var query = from c in context.Cities where c.CityID == 3 select c;
var objectQuery=query as System.Data.Objects.ObjectQuery;
Console.WriteLine(objectQuery.ToTraceString());

这将输出以下字符串:

SELECT
[Extent1].[CityID] AS [CityID],
[Extent1].[geom] AS [geom],
[Extent1].[Name] AS [Name],
FROM [dbo].[Cities] AS [Extent1]
WHERE 3 = [Extent1].[CityID]

我的表格包含名为geometry的空间​​列。实体框架不包含几何函数。例如,这是一个几何函数:

SELECT ST_AREA(geom) FROM Cities WHERE CityID = 3

所以我不能像这样使用上下文扩展方法:

context.Cities.Where(....)

是否可能,或者是否有任何实体框架方法来覆盖几何函数。

2 个答案:

答案 0 :(得分:1)

您无需覆盖任何内容。最好的办法是通过Entity Framework执行一个简单的SQL查询,让它返回你的填充对象。

// Add in whatever spatial stuff you need here.
var sql = "SELECT * FROM Cities WHERE CityId = {0} AND ...";

// Add whatever other parameters you need to the rest of the parameters.
var cities = context.Database.SqlQuery<City>(sql, cityId, ...);

它不像使用LINQ那样“干净”,但我认为实施一个打包到EF的LINQ to Entities解决方案的后勤是他们尚未完成的原因。您可以尝试这样做,但有一个更容易的解决方案。

答案 1 :(得分:1)

从EF 6.0(数据库优先)开始,应该有可能使用sql函数。它是通过EdmFunction属性完成的。请参阅示例http://blogs.msdn.com/b/efdesign/archive/2008/10/08/edm-and-store-functions-exposed-in-linq.aspx

在他们展示的博客文章中:

var query = 
    from p in context.Products 
    where EntityFunctions.DiffYears(DateTime.Today, p.CreationDate) < 5 
    select p;

其中EntityFunctions.DiffYears是函数

使用EF 6.1,此功能应该已扩展到Code First。请参阅示例http://blog.3d-logic.com/2014/04/09/support-for-store-functions-tvfs-and-stored-procs-in-entity-framework-6-1/

相关问题