【问题标题】:LINQ to Entities does not recognise custom methodLINQ to Entities 无法识别自定义方法
【发布时间】:2012-08-27 21:02:11
【问题描述】:

下面的代码会产生错误:

LINQ to Entities 无法识别方法System.String GenerateSubscriptionButton(Int32) 方法,并且该方法无法转换为存储表达式。

如何在 LINQ to Entities 中创建正确的自定义方法?

var model = _serviceRepository.GetProducts().Select(p => new ProductModel
{
    Id = p.Id,
    Name = p.Name,
    Credits = p.Credits,
    Months = p.Months,
    Price = p.Price,
    PayPalButton = GenerateSubscriptionButton(p.Id)
});        

private string GenerateSubscriptionButton(int id)
{
    return new PaymentProcessor.PayPalProcessor().CreateSubscriptionButton(id);
}

【问题讨论】:

    标签: c# linq linq-to-entities


    【解决方案1】:

    你不能那样做。提供者应如何将您的方法转换为 SQL?

    记住:LINQ to Entities 实际上并不执行查询的 C# 代码。相反,它解释表达式并将它们转换为 SQL。

    在您的具体情况下,解决方案可能如下所示:

    var model = _serviceRepository.GetProducts()
                                  .Select(p => new ProductModel 
                                               { 
                                                   Id = p.Id, 
                                                   Name = p.Name, 
                                                   Credits = p.Credits, 
                                                   Months = p.Months, 
                                                   Price = p.Price
                                               })
                                  .ToList()
                                  .Select(x =>
                                          {
                                              x.PayPalButton = GenerateSubscriptionButton(x.Id);
                                              return x;
                                          }); 
    

    ToList 的调用对数据库执行到目前为止的查询并返回结果。从那时起,查询实际上是一个 LINQ to objects 查询,其中代码不被解释而是被执行。

    【讨论】:

      【解决方案2】:

      你不能。问题是,你不能从 SQL 调用GenerateSubscriptionButton

      您需要检索实体,然后一旦它们在内存中,您就可以调用GenerateSubscriptionButton。在将实体投影到模型上之前,您可以通过添加对 AsEnumerable 的调用来实现这一点。

      var model = _serviceRepository.GetProducts()
          .AsEnumerable()
          .Select(p => new ProductModel
                           {
                               Id = p.Id,
                               Name = p.Name,
                               Credits = p.Credits,
                               Months = p.Months,
                               Price = p.Price,
                               PayPalButton = GenerateSubscriptionButton(p.Id)
                           });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-09
        • 1970-01-01
        • 2012-04-03
        • 2021-11-06
        • 2012-05-03
        相关资源
        最近更新 更多