Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

c# - Add filter to all query entity framework

I want add CompanyID filter to my all entity framework request.Because each user must see just their records.I dont want add filter (x=>x.CompanyID == cID) all methods in business layer.How can i add automaticly filter to requests.

My GetList method in DAL

     public List<TEntity> GetList(Expression<Func<TEntity, bool>> filter)
    {
        using (var context = new TContext())
        {

            return filter == null
                ? context.Set<TEntity>().ToList()
                : context.Set<TEntity>().Where(filter).ToList();
        }
    }

Business

   public List<FinanceData> GetAll()
        {
            return _financeDal.GetList(filter:x=>x.CompanyID==_cID);
        }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In the Entity Framework Core 2.0, you can use Global Query Filters.

  1. Add filter just to the one entity:

    public interface IDelete
    {
        bool IsDeleted { get; set; }
    }
    
    public class Blog : IDelete
    {        
        public int BlogId { get; set; }
        public string Name { get; set; }
        public string Url { get; set; }
    
        public List<Post> Posts { get; set; }
    }
    
    public class Post : IDelete
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public bool IsDeleted { get; set; }
    
        public int BlogId { get; set; }
        public Blog Blog { get; set; }
    }
    
    // Default method inside the DbContext or your default Context
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {         
        base.OnModelCreating(builder);  
    
        modelBuilder.Entity<Blog>()
                    // Add Global filter to the Blog entity
                    .HasQueryFilter(p => p.IsDeleted == false);
    
        modelBuilder.Entity<Post>()
                    // Add Global filter to the Post entity
                    .HasQueryFilter(p => p.IsDeleted == false);
    }
    
  2. If you have many entities, the first way isn't good, Use below code for applying the global filter to all entities(Magic way):

    public static class ModelBuilderExtension
    {
        public static void ApplyGlobalFilters<TInterface>(this ModelBuilder modelBuilder, Expression<Func<TInterface, bool>> expression)
        {
            var entities = modelBuilder.Model
                .GetEntityTypes()
                .Where(e => e.ClrType.GetInterface(typeof(TInterface).Name) != null)
                .Select(e => e.ClrType);
            foreach (var entity in entities)
            {
                var newParam = Expression.Parameter(entity);
                var newbody = ReplacingExpressionVisitor.Replace(expression.Parameters.Single(), newParam, expression.Body);    
                modelBuilder.Entity(entity).HasQueryFilter(Expression.Lambda(newbody, newParam));
            }
        }
    }
    
    // Default method inside the DbContext or your default Context
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    
        modelBuilder.Entity<Blog>();
        modelBuilder.Entity<Post>();
    
        builder.ApplyGlobalFilters<IDelete>(e => e.IsDeleted == false);
    }
    

And Queries will be:

    exec sp_executesql N'SELECT [x].[BlogId], [x].[Name], [x].[Url]
    FROM [dbo].[Blog] AS [x]
    WHERE [x].[IsDeleted] = 0'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...