我的数据库中有 3 个正在使用的表:
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);
}