Adding Where Condition to All Requests EF6
Asked Answered
W

1

5

Most of my entities (not all) have two properties called CompanyId and Deleted. How would be possible to auto insert these two properties for all select requests instead of setting manually on every single query I have along the whole app.

Example:

db.MyEntity.Where(me => me.Id == 1).Select(me => me.Description)
  • Check dynamically it the entity has the props CompanyId and Deleted.
  • Case affirmative, transform it like this

db.MyEntity.Where(me => me.Id == 1 && Deleted == false && CompanyId == 1).Select(me => me.Description)

  • Case negative, keep the same select query.

It would help me having to set these conditions to all my queries in which has the properties available.

Wojak answered 15/12, 2016 at 1:19 Comment(0)
G
7

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<IMyEntityInterface, int, bool>("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
Genarogendarme answered 15/12, 2016 at 6:37 Comment(3)
Thank you for your reply. I chose [nuget.org/packages/EntityFramework.DynamicFilters/] that is a bit more mature.Wojak
The filter MyFilter is global yes, but the filter with id=1, and isDelete=false is only applicable to the one instance of the query. This is what it seems like from the code above. How can i set the filter values once and for all, in one place ?Calderon
@pnizzle, you can call EnableFilter and set paramaters.at context's constructor.Genarogendarme

© 2022 - 2024 — McMap. All rights reserved.