原文地址:https://aspnetboilerplate.com/Pages/Documents/Articles%5CHow-To%5Cadd-custom-data-filter-ef-core

在本文中,我将解释如何在EF core中添加自定义数据过滤器。

我们将为OrganizationUnit 创建一个过滤器,并从IMayHaveOrganizationUnit接口继承的实体,根据登录用户的组织单元自动过滤。

我们将使用asp.net core和asp.net查询模板。您可以在https://aspnetboilerplate.com/templates上创建一个项目,并应用以下步骤来查看自定义组织单元筛选器的运行情况。

创建和更新实体

创建实体

创建名为Document的实体继承自IMayHaveOrganizationUnit接口(IMayHaveOrganizationUnit接口在abp框架中定义)。

public class Document : Entity, IMayHaveOrganizationUnit
{
public string Title { get; set; } public string Content { get; set; } public long? OrganizationUnitId { get; set; }
}

  在你的DbContext中添加Document实体

更新User类

向user.cs添加OrganizationUnitId。我们将使用用户的OrganizationUnitId 字段来过滤Document实体。

public class User : AbpUser<User>
{
public const string DefaultPassword = "123qwe"; public static string CreateRandomPassword()
{
return Guid.NewGuid().ToString("N").Truncate(16);
} public int? OrganizationUnitId { get; set; } public static User CreateTenantAdminUser(int tenantId, string emailAddress)
{
var user = new User
{
TenantId = tenantId,
UserName = AdminUserName,
Name = AdminUserName,
Surname = AdminUserName,
EmailAddress = emailAddress
}; user.SetNormalizedNames(); return user;
}
}

  

添加迁移

使用add migration命令添加迁移并运行update database以将更改应用于数据库。

创建Claim

我们需要在Claim中存储登录用户的OrganizationUnitId ,这样就可以得到它,以便在DbContext中过滤IMayHaveOrganizationUnit 实体。为此,重写UserClaimsPrincipalFactory类的CreateAsync方法,并将登录用户的 OrganizationUnitId 添加到如下声明中。

public class UserClaimsPrincipalFactory : AbpUserClaimsPrincipalFactory<User, Role>
{
public UserClaimsPrincipalFactory(
UserManager userManager,
RoleManager roleManager,
IOptions<IdentityOptions> optionsAccessor)
: base(
userManager,
roleManager,
optionsAccessor)
{
} public override async Task<ClaimsPrincipal> CreateAsync(User user)
{
var claim = await base.CreateAsync(user);
claim.Identities.First().AddClaim(new Claim("Application_OrganizationUnitId", user.OrganizationUnitId.HasValue ? user.OrganizationUnitId.Value.ToString() : "")); return claim;
}
}

  

注册过滤器

在筛选DbContext中的实体之前,我们将注册过滤器,以便在代码中的某些情况下禁用它。

在YourProjectNameEntityFrameworkModule 的PreInitialize 方法中注册筛选器,以从当前工作单元管理器获取它。

public override void PreInitialize()
{
... //register filter with default value
Configuration.UnitOfWork.RegisterFilter("MayHaveOrganizationUnit", true);
}

  

配置DbContext

我们需要使用OrganizationUnitId 的值来过滤DbContext中的IMayHaveOrganizationUnit 实体。

为此,首先在DbContext中添加如下字段:

protected virtual int? CurrentOUId => GetCurrentUsersOuIdOrNull();

在DbContext中定义如下GetCurrentUsersOuIdOrNull方法,并使用propert注入将IPrincipalAccessor 注入到DbContext中;

public class CustomFilterSampleDbContext : AbpZeroDbContext<Tenant, Role, User, CustomFilterSampleDbContext>
{
public DbSet<Document> Documents { get; set; } public IPrincipalAccessor PrincipalAccessor { get; set; } protected virtual int? CurrentOUId => GetCurrentUsersOuIdOrNull(); public CustomFilterSampleDbContext(DbContextOptions<CustomFilterSampleDbContext> options)
: base(options)
{ } protected virtual int? GetCurrentUsersOuIdOrNull()
{
var userOuClaim = PrincipalAccessor.Principal?.Claims.FirstOrDefault(c => c.Type == "Application_OrganizationUnitId");
if (string.IsNullOrEmpty(userOuClaim?.Value))
{
return null;
} return Convert.ToInt32(userOuClaim.Value);
}
}

  之后,让我们向DbContext添加一个属性,以获取MayHaveOrganizationUnit 过滤器是否已启用。

protected virtual bool IsOUFilterEnabled => CurrentUnitOfWorkProvider?.Current?.IsFilterEnabled("MayHaveOrganizationUnit") == true;

  

AbpDbContext 定义了两个与数据筛选器相关的方法。一个是ShouldFilterEntity ,另一个是CreateFilterExpression。ShouldFilterEntity方法决定是否过滤实体。CreateFilterExpression方法为要筛选的实体创建筛选表达式。

为了过滤从IMayHaveOrganizationUnit继承的实体,我们需要重写这两个方法。

首先,重写如下所示的ShouldFilterEntity 方法;

protected override bool ShouldFilterEntity<TEntity>(IMutableEntityType entityType)
{
if (typeof(IMayHaveOrganizationUnit).IsAssignableFrom(typeof(TEntity)))
{
return true;
} return base.ShouldFilterEntity<TEntity>(entityType);
}

然后,重写CreateFilterExpression方法,如下所示;

protected override Expression<Func<TEntity, bool>> CreateFilterExpression<TEntity>()
{
var expression = base.CreateFilterExpression<TEntity>(); if (typeof(IMayHaveOrganizationUnit).IsAssignableFrom(typeof(TEntity)))
{
Expression<Func<TEntity, bool>> mayHaveOUFilter = e => ((IMayHaveOrganizationUnit)e).OrganizationUnitId == CurrentOUId || (((IMayHaveOrganizationUnit)e).OrganizationUnitId == CurrentOUId) == IsOUFilterEnabled;
expression = expression == null ? mayHaveOUFilter : CombineExpressions(expression, mayHaveOUFilter);
} return expression;
}

  以下是DbContext的最终版本:

public class CustomFilterSampleDbContext : AbpZeroDbContext<Tenant, Role, User, CustomFilterSampleDbContext>
{
public DbSet<Document> Documents { get; set; } public IPrincipalAccessor PrincipalAccessor { get; set; } protected virtual int? CurrentOUId => GetCurrentUsersOuIdOrNull(); protected virtual bool IsOUFilterEnabled => CurrentUnitOfWorkProvider?.Current?.IsFilterEnabled("MayHaveOrganizationUnit") == true; public CustomFilterSampleDbContext(DbContextOptions<CustomFilterSampleDbContext> options)
: base(options)
{ } protected override bool ShouldFilterEntity<TEntity>(IMutableEntityType entityType)
{
if (typeof(IMayHaveOrganizationUnit).IsAssignableFrom(typeof(TEntity)))
{
return true;
}
return base.ShouldFilterEntity<TEntity>(entityType);
} protected override Expression<Func<TEntity, bool>> CreateFilterExpression<TEntity>()
{
var expression = base.CreateFilterExpression<TEntity>();
if (typeof(IMayHaveOrganizationUnit).IsAssignableFrom(typeof(TEntity)))
{
Expression<Func<TEntity, bool>> mayHaveOUFilter = e => ((IMayHaveOrganizationUnit)e).OrganizationUnitId == CurrentOUId || (((IMayHaveOrganizationUnit)e).OrganizationUnitId == CurrentOUId) == IsOUFilterEnabled;
expression = expression == null ? mayHaveOUFilter : CombineExpressions(expression, mayHaveOUFilter);
} return expression;
} protected virtual int? GetCurrentUsersOuIdOrNull()
{
var userOuClaim = PrincipalAccessor.Principal?.Claims.FirstOrDefault(c => c.Type == "Application_OrganizationUnitId");
if (string.IsNullOrEmpty(userOuClaim?.Value))
{
return null;
} return Convert.ToInt32(userOuClaim.Value);
}
}

  

测试过滤器

要测试MayHaveOrganizationUnit筛选器,请创建一个组织单元,并将其用户ID设置为2(默认租户的管理用户的ID)和TenantID设置为1(默认租户的ID)。然后,在数据库中创建文档记录。用组织机构的OrganizationUnitId 设置默认租户管理员和已创建的文档。

在HomeController中从数据库获取数据:

[AbpMvcAuthorize]
public class HomeController : CustomFilterSampleControllerBase
{
private readonly IRepository<Document> _documentRepository; public HomeController(IRepository<Document> documentRepository)
{
_documentRepository = documentRepository;
} public ActionResult Index()
{
var documents = _documentRepository.GetAllList();
var documentTitles = string.Join(",", documents.Select(e => e.Title).ToArray()); return Content(documentTitles);
}
}

当您以host 用户身份登录时,应该会看到一个emtpy页面。但是,如果您以默认租户的管理员用户身份登录,您将看到以下文档标题:(以下丢失一张图片,请自行脑补,O(∩_∩)O哈哈~)

禁用筛选器

可以禁用如下筛选器:

[AbpMvcAuthorize]
public class HomeController : CustomFilterSampleControllerBase
{
private readonly IRepository<Document> _documentRepository;
private readonly IUnitOfWorkManager _unitOfWorkManager; public HomeController(IRepository<Document> documentRepository, IUnitOfWorkManager unitOfWorkManager)
{
_documentRepository = documentRepository;
_unitOfWorkManager = unitOfWorkManager;
} public ActionResult Index()
{
using (_unitOfWorkManager.Current.DisableFilter("MayHaveOrganizationUnit"))
{
var documents = _documentRepository.GetAllList();
var documentTitles = string.Join(",", documents.Select(e => e.Title).ToArray()); return Content(documentTitles);
}
}
}

  在这种情况下,将从数据库检索所有文档记录,而不管登录用户OrganizationUnitId是什么。

翻译完成,但并不是我想要的功能 ┭┮﹏┭┮

文章翻译:ABP如何在EF core中添加数据过滤器的更多相关文章

  1. 9.翻译系列:EF 6以及EF Core中的数据注解特性(EF 6 Code-First系列)

    原文地址:http://www.entityframeworktutorial.net/code-first/dataannotation-in-code-first.aspx EF 6 Code-F ...

  2. 9.4 翻译系列:EF 6以及 EF Core中的NotMapped特性(EF 6 Code-First系列)

    原文链接:http://www.entityframeworktutorial.net/code-first/notmapped-dataannotations-attribute-in-code-f ...

  3. 20.1翻译系列:EF 6中自动数据迁移技术【EF 6 Code-First系列】

    原文链接:https://www.entityframeworktutorial.net/code-first/automated-migration-in-code-first.aspx EF 6 ...

  4. 11.翻译系列:在EF 6中配置一对零或者一对一的关系【EF 6 Code-First系列】

    原文链接:https://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-fi ...

  5. EF Core中避免贫血模型的三种行之有效的方法(翻译)

    Paul Hiles: 3 ways to avoid an anemic domain model in EF Core 1.引言 在使用ORM中(比如Entity Framework)贫血领域模型 ...

  6. 如何在EF Core 使用存储过程

    使用EF Core框架能快速的帮助我们进行常规的数据处理和项目开发,但是ORM虽然好用,但是在许多复杂逻辑的数据处理时,我个人还是偏向用SQL和存储过程的方式去处理,但是研究了一下目前最新版本的EF ...

  7. 项目开发中的一些注意事项以及技巧总结 基于Repository模式设计项目架构—你可以参考的项目架构设计 Asp.Net Core中使用RSA加密 EF Core中的多对多映射如何实现? asp.net core下的如何给网站做安全设置 获取服务端https证书 Js异常捕获

    项目开发中的一些注意事项以及技巧总结   1.jquery采用ajax向后端请求时,MVC框架并不能返回View的数据,也就是一般我们使用View().PartialView()等,只能返回json以 ...

  8. EF Core中的多对多映射如何实现?

    EF 6.X中的多对多映射是直接使用HasMany-HasMany来做的.但是到了EF Core中,不再直接支持这种方式了,可以是可以使用,但是不推荐,具体使用可以参考<你必须掌握的Entity ...

  9. EF Core中执行Sql语句查询操作之FromSql,ExecuteSqlCommand,SqlQuery

    一.目前EF Core的版本为V2.1 相比较EF Core v1.0 目前已经增加了不少功能. EF Core除了常用的增删改模型操作,Sql语句在不少项目中是不能避免的. 在EF Core中上下文 ...

随机推荐

  1. 常用的 Git 命令,给你准备好了!

    分支操作: git branch 创建分支 git branch -b 创建并切换到新建的分支上 git checkout 切换分支 git branch 查看分支列表 git branch -v 查 ...

  2. Java第七周课堂示例总结

    一.super();调用基类构造方法 代码: class Grandparent{ public Grandparent(){ System.out.println("GrandParent ...

  3. 【pytorch】学习笔记(二)- Variable

    [pytorch]学习笔记(二)- Variable 学习链接自莫烦python 什么是Variable Variable就好像一个篮子,里面装着鸡蛋(Torch 的 Tensor),里面的鸡蛋数不断 ...

  4. MYSQL中的UNION和UNION ALL

    SQL UNION 操作符 UNION 操作符用于合并两个或多个 SELECT 语句的结果集. 请注意,UNION 内部的 SELECT 语句必须拥有相同数量的列.列也必须拥有相似的数据类型.同时,每 ...

  5. python并发编程-进程理论-进程方法-守护进程-互斥锁-01

    操作系统发展史(主要的几个阶段) 初始系统 1946年第一台计算机诞生,采用手工操作的方式(用穿孔卡片操作) 同一个房间同一时刻只能运行一个程序,效率极低(操作一两个小时,CPU一两秒可能就运算完了) ...

  6. 安装Python环境

    首先我们来安装Python,Python3.5+以上即可 1.首先进入网站下载:点击打开链接(或自己输入网址https://www.python.org/downloads/),进入之后如下图,选择图 ...

  7. Python和其他编程语言

    Python和其他编程语言 一.Python介绍 Python的创始人为吉多·范罗苏姆(Guido van Rossum),如下图,少数几个不秃头的语言创始人.1989年的圣诞节期间,Guido为了打 ...

  8. 2019-2020Nowcoder Girl初赛题解

    写了一天计算几何,心态崩了,水一篇题解休息休息. emmmm,如果您是一名现役OIer/CSPer,那看这篇文章也许并不能在你的生命中留下些什么(潮子语录),因为相比NOIP/CSP这个比赛其实比较简 ...

  9. 上海的Costco,谈谈你的理解和感受

    众所周知,Costco在上海第一天开业,由于人流量过大,一度暂停营业.我觉得Costco的成功在于不走寻常路,换位思考(站在用户.厂商角度看问题),下面几点是我觉得它做得比较独特的地方: 1. Cos ...

  10. 第七篇 CSS盒子

    CSS盒子模型   在页面上,我们要控制元素的位置,比如:写作文一样,开头的两个字会空两个格子(这是在学校语文作文一样),其后就不会空出来,还有,一段文字后面跟着一张图,它们距离太近,不好看,我们要移 ...