避免同一次查询两次? (在页面和主页中)

时间:2015-04-07 09:29:02

标签: c# asp.net master-pages

我的网站上有一个看起来像这样的网页:

public partial class MyPage : System.Web.UI.Page
{
    private MyPageService service = new MyPageService();
    private User user;

    protected void Page_Load(object sender, EventArgs e)
    {
        user = service.CurrentUser;

        if (user != null)
            DoSomethingUsingUser();
    }
}

我的问题是主页还需要取回当前经过身份验证的用户才能更新其内容(用户金额,新消息等),并执行一些操作,例如注销。

public partial class MyMasterPage : System.Web.UI.MasterPage
{
    private User user;

    protected void Page_Load(object sender, EventArgs e)
    {
        user = ...;
        UpdatePage();
    }

    private void UpdateMoney()
    {
        if (user != null)
            _Money.Text = "Money: " + user.Money;
    }

    private void UpdateNewMessages()
    {
        _NewMessage.Visible = (user != null) && user.HasNewMessages();
    }

    private void UpdatePage()
    {
        UpdateNewMessages();
        UpdateMoney();
    }

    protected void _LogOut_Click(object sender, EventArgs e)
    {
        ...
    }
}

所以我的问题是" MyMasterPage"是" MyPage"的主页,是否有一种干净的方式来共享页面与其母版页之间的当前用户对象,而不是两次查询数据库,一次在页面和一次在主人? 或者我应该查询两次?

非常感谢!

如果它可能有用:

以下是MyPage中使用的服务:

public class MyPageService : CommonAuthenticatedService
{
    public MyService()
    {
    }

    ...
    SomeSpecificMethods();
    ...

    # region Override

    // Loads user resources specifically required for MyPage page
    protected override IQueryable<User> LoadUserResources(DbSet<User> users)
    {
        return users
            .Include(x => x.SomeProperty1)
            .Include(x => x.SomeProperty2)
            .Include(x => x.SomeProperty3)
            ...;
    }

    # endregion Override
}

常用服务,用于需要经过身份验证的用户的每项服务:

public abstract class CommonAuthenticatedService
{
    public User CurrentUser { get; private set; }
    protected UserRepo userRepo = new UserRepo();

    public CommonAuthenticatedService()
    {
        SetCurrentUser();
    }

    protected abstract IQueryable<User> LoadPlayerResources(DbSet<User> users);

    private void SetCurrentUser()
    {
        using (var uof = new UnitOfWork())
        {
            Guid? currentUserId = userRepo.GetCurrentId();

            if (currentUserId.HasValue)
            {
                DbSet<User> users = userRepo.GetDbSet();

                CurrentUser = LoadUsersResources(users)
                    .SingleOrDefault(e => (e.Id == (Guid)currentUserId));
            }
        }
    }
}

0 个答案:

没有答案