3

考慮以下查詢:你如何在Entity Framework中重用select語句?

var query = from item in context.Users // Users if of type TblUser 
      select new User()   // User is the domain class model 
      { 
       ID = item.Username, 
       Username = item.Username 
      }; 

我怎樣才能重新使用在其他的查詢語句的選擇部分?即

var query = from item in context.Jobs // Jobs if of type TblJob 
      select new Job()   // Job is the domain class model 
      { 
       ID = item.JobId, 
       User = ReuseAboveSelectStatement(item.User); 
      }; 

我試着只使用一個映射器的方法:

public User MapUser(TblUser item) 
{ 
    return item == null ? null : new User() 
    { 
     ID = item.UserId, 
     Username = item.Username 
    }; 
} 

有了:

var query = from item in context.Users // Users if of type TblUser 
      select MapUser(item); 

但如果我這樣做,那麼框架拋出一個錯誤,如:

LINQ to Entities不識別 我「方法」MapUser(TblUser)'方法, 並且此方法不能將 轉換成存儲表達式。

回答

1

您不能在像這樣的查詢定義中使用常規函數調用。 LINQ需要表達式樹,它不能分析已編譯的函數並將其神奇地轉換爲SQL。 Read this for a more elaborate explanation

的引用的文章中所使用的技術納入linqkit(分解出謂詞)和可能的幫助,雖然我不知道你可以使用同樣的技術,用於管理的預測,這是你彷彿想。

更重要的問題,你應該問自己在這裏恕我直言,是否你真的需要這個額外的映射層?看起來你正在實施EF已經完全有能力爲你做的事情......

+2

把它這樣,我不想寫'User = new User(){UserId = item.User.UserId,UserName = item.User.Username,NField = item.User.etc}'大約30次。 – GenericTypeTea 2010-08-03 07:52:08

0

試着製作你的MapUser方法static

+0

沒有什麼區別。 – GenericTypeTea 2010-08-01 20:55:26

+0

嗯...似乎將它固定在L2S中,但不是在EF中。你可能會看看這篇文章,但:http://blogs.msdn.com/b/efdesign/archive/2008/10/08/edm-and-store-functions-exposed-in-linq.aspx – Yakimych 2010-08-01 22:02:23