【问题标题】:Can SQL level functions be made available to LINQ to Entity queries?SQL 级别的函数是否可用于 LINQ to Entity 查询?
【发布时间】:2012-05-17 07:19:44
【问题描述】:

我希望我可以编写调用其他函数的 LINQ to Entity 查询:

from c in context.Widgets
where MyFunc(c.name)
select c

这会导致错误,因为表达式显然无法转换为调用 MyFunc 的 TSQL。

嗯,我在想,除非 MyFunc 是用户定义的函数或(我认为更好)SQL/CLR 函数。

那么这可能吗,而且是否推荐?

如果不可能,我希望拥有此功能是否有效并且可能会在 ADO.NET 的未来中得到解决?

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    您应该在数据库中创建一个用户定义的函数MyFunc 并将其手动“导入”到您的上下文中(edmx,因此首先是数据库),无论是在 XML 中还是作为上下文类的部分类中的存根.此处描述了该过程:

    How to use a custom database function(请注意,“StorageNamespace”是您在<edmx:StorageModels><Schema Namespace=... 下的 XML 文件中找到的命名空间。

    MSDN 有类似的描述。

    【讨论】:

      【解决方案2】:

      EF 致力于将 .net 类与数据库结构同步,并且最适合在数据库是哑巴且所有逻辑都位于类中的情况下。

      但是你可以映射到函数和存储过程——解释起来有点技术性(做起来容易得多)——让我为你找到一些链接。

      这是一个不好的方法:

      // Query that calls the OrderTotal function to recalculate the order total.
      string queryString = @"USING Microsoft.Samples.Entity;
          FUNCTION OrderTotal(o SalesOrderHeader) AS
          (o.SubTotal + o.TaxAmt + o.Freight)
      
          SELECT [order].TotalDue AS currentTotal, OrderTotal([order]) AS calculated
          FROM AdventureWorksEntities.SalesOrderHeaders AS [order]
          WHERE [order].Contact.ContactID = @customer";
      
      int customerId = 364;
      
      
      using (AdventureWorksEntities context =
          new AdventureWorksEntities())
      {
          ObjectQuery<DbDataRecord> query = new ObjectQuery<DbDataRecord>(queryString, context);
          query.Parameters.Add(new ObjectParameter("customer",customerId));
      
          foreach (DbDataRecord rec in query)
          {
              Console.WriteLine("Order Total: Current - {0}, Calculated - {1}.", 
                  rec[0], rec[1]);
          }
      }
      

      http://msdn.microsoft.com/en-us/library/dd490951.aspx

      正确的做法如下:

      http://scipbe.wordpress.com/2010/08/30/stored-procedures-udfs-in-the-entity-framework-part-1/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-10
        • 1970-01-01
        • 1970-01-01
        • 2012-04-04
        相关资源
        最近更新 更多