Adding Where Condition to All Requests EF6

后端 未结 1 1177
悲哀的现实
悲哀的现实 2021-01-13 09:36

Most of my entities (not all) have two properties called CompanyId and Deleted. How would be possible to auto insert these two pro

1条回答
  •  伪装坚强ぢ
    2021-01-13 10:08

    You can add filter with the help of nuget package: EntityFramework.Filters. Also, good idea is to create common interface instead of dynamically checking for properties existence:

    public interface IMyEntityInterface
    {
        public int Id {get;set;}
        public bool Deleted {get;set;}
    }
    
    public class MyEntity : IMyEntityInterface
    {
        public int Id {get;set;}
        public bool Deleted {get;set;}
        //other stuff
    }
    
    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    {   
        modelBuilder.Conventions
           .Add(FilterConvention.Create("MyFilter", (entity, Id, Deleted) => entity.Id == Id && entity.Deleted == Deleted);
    }
    

    Usage:

    var filter = db.EnableFilter("MyFilter");
    filter.SetParameter("Id", 1);
    filter.SetParameter("Deleted", false);
    
    var data = db.MyEntity.Where(me => me.CompanyId == 1).Select(me => me.Description);
    //select Description from MyEntities where Id = 1 and Deleted = false and CompanyId = 1
    

    0 讨论(0)
提交回复
热议问题