2014-01-24 46 views
1

使用我们以前的ORM,OpenAccess,我们能够在查询的select语句中包含帮助器方法。例如,将SQL数据与高速缓存的应用程序数据组合在一起。在实体框架查询中使用帮助器方法

切换到实体框架6.x中后我们得到象这样的错误:

LINQ到实体无法识别方法“System.String GetProductTranslation”

的灵查询看起来是这样的:

var products = (from p in db.Products 
       join cp in db.CustomerPrices on p.ProductId equals cp.ProductId 

       where p.LockedSince.Equals(null) 
       && ... etc etc etc 

       select new 
       { 
        ProductId = p.ProductId, 
        Name = TranslationHelper.GetProductTranslation(p.ProductId, ProductTranslationField.Name, p.Name), 
        Description2 = TranslationHelper.GetProductTranslation(p.ProductId, ProductTranslationField.Description2, p.Description2), 
        Description3 = TranslationHelper.GetProductTranslation(p.ProductId, ProductTranslationField.Description3, p.Description3), 
        Description4 = TranslationHelper.GetProductTranslation(p.ProductId, ProductTranslationField.Description4, p.Description4), 
        ... etc etc etc 
       }); 

在这种情况下,GetProductTranslation方法从应用程序缓存抓住转换数据防止在数据库中使用无限量的连接和压力。

使用Entity Framework 6.x复制这个最好的方法是什么?

+1

为什么只是没有通过sql查询拆分出来那会返回产品的神经数据和另一种方法来检索你从缓存中获取的内容? –

回答

1

您不能使用自定义的方法与查询syntax.You可以看到支持的方法here

相反,你应该使用Extension methods这样的:

db.Products.Join(db.CustomerPrices, 
       p => p.ProductId, 
       c => c.ProductId, 
       (p,c) => new { Product = p, cust = c }) 
      .Where(p => p.Product.LockedSince.Equals(null)) 
      .Select(p => new { 
         ProductId = p.Product.ProducId, 
         Name = TranslationHelper.GetProductTranslation(p.Product.ProductId, ProductTranslationField.Name, p.Product.Name), 
         ... 
         }); 
+0

我不确定你的代码示例是什么。我能看到的只是使用lambda语法。切换到其他语法对EF引发的异常没有什么影响。 现在我已经分开了两个,就像上面弗拉基米尔Shmidt建议的那样。但我仍然喜欢看到像我们以前那样整合在一起。 – Erik

+0

@Erik,您的查询在幕后转换此lambda语法,但查询synxtax中存在限制。您尝试在查询语法中使用不受支持的方法时无法使用不受支持的方法,因此无法识别它,因为没有映射这个方法。直接使用lambda语法,你可以使用任何你想要的 –