【发布时间】:2015-09-09 00:20:30
【问题描述】:
我正在尝试构建一个多租户 MVC Web 应用程序,目前进展顺利。在我的应用程序中,我扩展了 asp.net Identity 2 User 属性以包含一个 OrganisationId,其中创建的每个用户都分配给一个组织。即 1 个组织可以有许多与之关联的用户。数据库可以有许多组织。
这是我之前的一篇文章,展示了我如何extended asp.net identity and retrieve the OrganisationId of the logged in user。
为了实现实体框架的全局过滤,让登录的用户只能看到他们关联的组织数据,我使用的是github上的Entity Framework Dynamic Filter。
我已经设法根据 github 提供的示例代码使全局过滤器工作,我在其中创建了一个静态属性 DBContext 可以根据登录的用户动态更新。
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
// A static/globally scoped value that will be used to restrict queries by their OrganisationId.
public static long CurrentUserOrganisationID { get; set; }
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
....
//Filters
modelBuilder.Filter("Employees_CurrentOrganisation", (Employee e) => e.OrganizationId, () => CurrentUserOrganisationID);
}
}
我面临的问题是我应该在我的 MCV 应用程序的哪个位置设置/刷新 DBContext 中的当前用户 OrganisationId 静态属性?我可以在登录过程中设置它,但是如果用户在没有单击“注销”的情况下退出应用程序,应用程序将记住他们下次浏览应用程序时已登录并且不执行登录控制器方法。
设置静态OrganisationId属性需要执行的代码是:
ApplicationDbContext.CurrentUserOrganisationID = Convert.ToInt64(HttpContext.User.Identity.GetOrganizationId());
对于这篇文章的标题,我深表歉意,我不确定提出问题的最佳术语! (新手提醒)
【问题讨论】:
-
'我在 DBContext 中创建了一个静态属性,该属性可以根据登录的用户动态更新' - 如果两个用户在同一时间?
-
无论如何,静态都是静态的。每个 AppDomain 将拥有一个
ApplicationDbContext.CurrentUserOrganisationID,而不是每个请求或用户。为什么不只使用声明? -
您好,感谢您的回复。我想在我的 DBContext 中使用静态属性不是一个好主意。运行测试后,我可以确认您是正确的。我真傻!我只是按照动态过滤器的可下载 github 示例中所示的示例进行操作。不知道我应该如何在登录时根据用户设置过滤器。当用户登录时会创建一个声明来存储声明,我只需要一种方法来为登录的各个用户设置过滤器。
标签: asp.net-mvc entity-framework asp.net-identity-2