2014-01-24 47 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語法,你可以使用任何你想要的 –