【发布时间】:2015-06-05 01:39:46
【问题描述】:
在我的网站中,每个 page_load 中检索到的当前用户有很多依赖项(总共 13 个):
public User Get(Guid userId)
{
MyEntities entities = _contextManager.Context;
User user = entities.Users
.Include(x => x.Something1)
.Include(x => x.Something2)
.Include(x => x.Something3)
.Include(x => x.Something4)
.Include(x => x.Something5)
.Include(x => x.Something6)
.Include(x => x.Something7)
.Include(x => x.Something8)
.Include(x => x.Something9)
.Include(x => x.Something10)
.Include(x => x.Something11)
.Include(x => x.Something12)
.Include(x => x.Something13.Select(s => s.Something14))
.SingleOrDefault(u => (u.Id == userId));
return user;
}
但这需要很长时间才能保持这样的状态。 但是,我不需要每个页面中的所有这些相关对象。 因此,我认为我可以做类似的事情:
public partial class MyPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
App.GetCurrentUser(this);
}
}
在 GetCurrentUser 中:
public static void GetCurrentUser(System.Web.UI.Page page)
{
// Here only load data required by the current page
}
这是一种不好的做法吗? 如果是,是否有任何适当的解决方案来进行包含加速器的查询?
非常感谢!
编辑
这是当前的 App.GetCurrentUser :
public static User GetCurrentUser()
{
using (UnitOfWork uow = new UnitOfWork())
{
if (Membership.GetUser() != null)
{
UserRepo userRepo = new UserRepo();
Guid guid = (Guid)Membership.GetUser().ProviderUserKey;
User user = userRepo.Get(guid); // the function with the 13 includes
return user;
}
}
}
【问题讨论】:
-
如果页面之外的方法不知道如何以通用方式获取对象,为什么它首先要获取对象?如果每个页面都必须执行不同的查询,则让每个页面执行自己的不同查询。
-
感谢您的回答!它是通用的并且可以工作,但是它太长了,因为即使当前页面不需要它,查询也会加载每个依赖项。我更新了第一篇文章以显示当前方法(调用包含 13 个函数的函数)
-
是的,因为您希望每个页面都有自己的一组包含,所以每个页面都有自己的查询,它会在其中写出它需要的所有包含。完毕。您正在概括要从多个地方调用的查询,这些地方对查询应该做什么有不同的要求。当您实际上想要相同的查询时,您应该重复使用相同的查询。
-
那我应该有GetUserForPage1()、GetUserForPage2()等吗?
-
只需让每个页面编写自己的查询。如果没有可添加的价值,则创建单独的通用查询管理器是没有意义的。
标签: c# asp.net entity-framework include conditional