The Entity Framework 6 does not have the ability to do nuget :
has the addition of features about Entity Framework 6 and one of them is to provide a global filter on your SQL
implicitly.
After installing the two packages and configuring your class, add a line inside the construtor
of the class that inherits from DbContext
. One scenario would be to recover all people with the Ativo = 1
, example field:
public DatabaseContext()
:base(ConnStr)
{
Database.SetInitializer<DatabaseContext>(null);
QueryFilterManager.Filter<People>(x => x.Where(a => a.Active == true));
}
or
Call the extension method Filter<>
, example :
public DatabaseContext()
:base(ConnStr)
{
Database.SetInitializer<DatabaseContext>(null);
this.Filter<People>(x => x.Where(a => a.Active));
}
In addition to the filters this is standard throughout the application, by name already says Global Query Filter . If any time in the application requires that this filter is not called, use the AsNoFilter()
, example method:
db.People.AsNoFilter().ToList();
The filter will not be added in SQL
.
Minimum complete example:
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using Z.EntityFramework.Plus;
namespace ConsoleApp41.Models
{
public class People
{
public int Id { get; set; }
public string Name { get; set; }
public bool Active { get; set; }
}
public class DatabaseContext: DbContext
{
protected const string ConnStr = "Connect_Strings";
public DatabaseContext()
:base(ConnStr)
{
Database.SetInitializer<DatabaseContext>(null);
QueryFilterManager.Filter<People>(x => x.Where(a => a.Active == true));
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<People>()
.ToTable("People");
modelBuilder.Entity<People>()
.HasKey(X => X.Id)
.Property(x => x.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
.IsRequired();
modelBuilder.Entity<People>()
.Property(x => x.Name)
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<People>()
.Property(x => x.Active)
.IsRequired();
}
public DbSet<People> People { get; set; }
}
}
The documentation has a variety of filters , but , on your doubt what is in the answer is the ideal for your development.
This feature is not present in the Entity Framework 6 , but Entity Framework Core already exists such a resource with the name of Global Query Filters , how to configure?
In the OnModelCreating
method, add a line as an example below:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<People>().HasQueryFilter(p => p.Active);
//
}
has the same effect as the example of the package installed in the 6 version and also can disable using the IgnoreQueryFilters()
var result = db.People.IgnoreQueryFilters().ToList();