Filter out every call created by DataContext when using LinQ objects

I use logical delete on my system and would like every call made to the database to be filtered automatically.

Let's say that I am loading data from the database like this:

product.Regions

      

How can I filter each request as it Regions

is EntitySet<Region>

and not a custom method, so I cannot addisDeleted = 0

I have found AssociateWith so far, but I would hate to write a line of code for each table -> Associations of the current project ...

I am studying either the structure of generic lambda expressions, or ... something else?

+2


source to share


2 answers


You can create an extension method that implements your filter and use it as a convention.

public static class RegionQuery
{
    public static IQueryable<Region> GetAll(this IQueryable<Region> query, bool excludeDeleted=true)
    {
        if (excludeDeleted)
            return query.Regions.Where(r => !r.isDeleted);

        return query.Regions;
    }
}

      

So whenever you want to query for regions, you can make the next call to get only live regions, which still provide the ability to get and remote.

context.Regions.GetAll();

      



This will be a little dependent on accessing the Products property, but still doable. The only problem is that you have to conform to the convention. Or extend the containing class.

someProduct.Regions.GetAll();

      

Hope this helps. This is what I ended up settling because I couldn't find a solution to this either beyond creating more indirection. Let me know if you or anyone else comes up with a solution to this problem. It is very interesting to me.

+1


source


It looks to me like you are using the relationship between the Product and Region classes. If so, then somewhere (the .dbml file for the auto-generated LINQ-to-SQL) there is a mapping that defines the relationship:

[Table(Name = "Product")]
public partial class Product
{
    ...
    private EntitySet<Region> _Regions;
    [Association(Storage = "_Regions")]
    public EntitySet<Region> Regions
    {
        get { return this._Regions; }
        set { this._Regions.Assign(value); }
    }
    ...
}

      

Here you can add some logic to the accessor like:



public IEnumerable<Region> Regions
{
    get { return this._Regions.Where(r => !r.isDeleted); }
    set { this._Regions.Assign(value); }
}

      

This way, every access through product.Regions returns your filtered Enumerable.

0


source







All Articles