2009-06-16 72 views
3

我的許多應用程序都使用complied查詢來檢索數據。在這些查詢中,我經常會引用當前用戶。我注意到,如果用戶B在另一個用戶A之後登錄,則用戶B將看到用戶A的信息。編譯查詢緩存?

我有疑問很像這一切都通過了申請

public static Func<DataContext, MyRecord> CurrentUserRecords = 
      CompiledQuery.Compile<DataContext, MyRecord>(
       (DataContext db) => 
        (from r in db.MyRecords 
        where 
         r.User == User.Current 
        select r).SingleOrDefault()); 

User.Current是取決於誰在登錄改變的靜態屬性。

public static User Current 
{ 
    get { return MyBase<User>.Get((int)(HttpContext.Current.Session["CurrentUserID"] ?? 0)); } 
} 

當我登錄首次使用用戶A,上面編譯的查詢返回用戶A的記錄。因此,User.Current也會返回對用戶A的適當引用。但是,當我以用戶B登錄時,儘管User.Current正在返回對用戶B的引用,但上述編譯後的查詢仍會返回用戶A的記錄。

我跑了SQL Server的Profiler,並注意到編譯查詢執行時生成的TSQL引用用戶A的ID兩次。

所以我的問題是這樣的:

不要編譯查詢莫名其妙緩存?

如果是這樣,那有什麼壽命,我可以控制它嗎?

是否在ASP.net應用程序的編譯查詢不良設計中引用「當前用戶」?

謝謝大家!

回答

2

您需要在已編譯的查詢中允許一個字符串參數。否則,它將在.Compile()期間解析字符串的值。試試這個:

public static Func<DataContext, string, MyRecord> UserRecordByParam = 
    CompiledQuery.Compile<DataContext, string, MyRecord> 
(
    (DataContext db, string UserName) => 
    db.MyRecords.Where(r => r.User == UserName).SingleOrDefault() 
); 

public static Func<DataContext, MyRecord> CurrentUserRecord = 
    (DataContext db) => UserRecordByParam(db, User.Current); 
+0

我很害怕這個。我目前已經掌握了CompliledQuery.compile重載將允許使用的參數數量。我確實發現這個雖然http://social.msdn.microsoft.com/forums/en-US/adodotnetentityframework/thread/f1fc5570-be6d-4d7f-b94f-aa5b6e9922cf/ – 2009-06-17 13:05:25