【问题标题】:Can I override Entity Framework query generator?我可以覆盖实体框架查询生成器吗?
【发布时间】:2015-02-27 12:56:59
【问题描述】:

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

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]

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

SELECT ST_AREA(geom) FROM Cities WHERE CityID = 3

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

context.Cities.Where(....)

可以吗,或者有没有实体框架方法可以覆盖几何函数。

【问题讨论】:

标签: c# entity-framework gis geospatial


【解决方案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 解决方案的后勤工作是他们尚未这样做的原因。您可以尝试这样做,但有一个更简单的解决方案。

【讨论】:

    【解决方案2】:

    从 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/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-05
      • 2011-05-06
      • 1970-01-01
      • 2012-03-09
      • 2017-09-03
      • 1970-01-01
      • 2015-02-02
      • 1970-01-01
      相关资源
      最近更新 更多