我在DB 3個表內,以我的工作:LINQ到實體查詢優化
Theme [Theme_ID]
ThemeWorkplace [Theme_ID, Workplace_ID, ThemeWorkplace_ID]
UserTheme [User_ID, Theme_ID, UserTheme_ID, UserTheme_AccessType]
我需要改變UserTheme_AccessType
所有UserTheme.Theme_ID
在當前工作場所與ThemeWorkplace.Workplace_ID = 2
與User_ID = 1
當前用戶。如果主題是UserTheme
中沒有這樣的用戶和這樣的主題行 - 我需要創建它。
我寫了這樣的代碼,但它工作時間過長:
var themeList = (from t in m_Entities.Theme
where (from tw in m_Entities.ThemeWorkplace
where tw.Workplace.Workplace_ID == 2
select tw.Theme.Theme_ID).Contains(t.Theme_ID)
select t)
.ToList();
foreach (Theme theme in themeList)
{
var oldUserTheme = GetByUserTheme(user/*user is given*/, theme);
if (oldUserTheme == null)
{
/* create new User Theme with params, that I need*/
this.Add(newUserTheme, true);
}
else
{
/* here - changing found row */
oldUserTheme.UserTheme_AccessType = 2;
}
}
我明白,這段代碼訪問數據庫的次數太多。我想找到一種方法來擺脫:
var oldUserTheme = GetByUserTheme(user/*user is given*/, theme);
在每foreach
迭代。有人可以幫我嗎?
添加GetByUserTheme()的代碼:
private UserTheme GetByUserTheme(User user, Theme theme)
{
return m_Entities.UserTheme.FirstOrDefault(ut => ut.User.User_ID == user.User_ID && ut.Theme.Theme_ID == theme.Theme_ID);
}
這可能是張貼的GetByUserTheme'如何'工作機制的細節是有用的。 – 2013-02-12 11:36:05
謝謝,我已經添加了GetByUserTheme聲明。 – 2013-02-12 11:45:48