选中Global Query Filters。
全局查询过滤器是LINQ查询谓词(布尔表达式
通常传递给应用于实体的LINQ Where查询运算符)
键入元数据模型(通常在OnModelCreating中)。这样的过滤器
自动应用于涉及那些实体的任何LINQ查询
类型,包括间接引用的实体类型,例如通过
使用包含或直接导航属性引用。
,
在这种情况下,我要做什么工作是创建一个包装DbContext
的类,并公开对其业务逻辑有意义的方法。根据您的情况,您可以创建UserRepository
/ StoreRepository
类,其中搜索方法需要origID
参数
public class StoreRepository {
private ApplicationDBContext _context
StoreRepository(ApplicationDBContext context){
_context = context
}
public Task<Ilist<Store>> GetStores(int origID){
return _context.Stores.Where(s => s.OrgID == orgID).ToListAsync();
}
}
,
创建一个具有OrgID的接口:
public interface IOrgID
{
public int OrgID { get; set; }
}
您的所有模型都必须实现此接口,例如:
public class ApplicationUser : IdentityUser,IOrgID
{
public int OrgID { get; set; }
//...
}
public class Stores : IOrgID
{
public int OrgID { get; set; }
//...
}
使用通用存储库并考虑当前登录用户的OrgID创建CRUD方法:
public class MyRepo
{
private readonly ApplicationDbContext _context;
private readonly IHttpContextAccessor _accessor;
private readonly int _orgID;
public MyRepo(ApplicationDbContext context,IHttpContextAccessor accessor)
{
_context = context;
_accessor = accessor;
var userId = _accessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
_orgID = _context.Users.Find(userId).OrgID;
}
public async Task<T> GetAsync<T>(Expression<Func<T,bool>> whereExp)
where T : class,IOrgId
{
return await _context.Set<T>().Where(x => x.OrgId == _orgID).FirstOrDefaultAsync(whereExp);
}
public async Task<bool> Create<T>(T entitiy)
where T : class,IOrgId
{
_context.Set<T>().Add(entitiy);
return await _context.SaveChangesAsync() > 0;
}
public async Task<bool> UpdateAsync<T>(T entity)
where T : class,IOrgId
{
_context.Entry<T>(entity).State = EntityState.Modified;
return await _context.SaveChangesAsync() > 0;
}
public async Task<IEnumerable<T>> ListAsync<T>(Expression<Func<T,IOrgId
{
return await _context.Set<T>().AsNoTracking().Where(x => x.OrgId == _orgID).Where(whereExp).ToListAsync();
}
public async Task<bool> DeleteAync<T>(T entity)
where T : class,IOrgId
{
_context.Entry<T>(entity).State = EntityState.Deleted;
return await _context.SaveChangesAsync() > 0;
}
}
本文链接:https://www.f2er.com/3140371.html