How to get child entities from a data constraint? [duplicate]

0

Well, my problem is the following, I need to bring an entity from the database and it contains several lists that should bring their data following a rule, the data_exclusao field should be null.

All entities have the data_exclusao field representing the logical exclusion of the data. Then follow an example to get better I have the person entity and it contains the lists of entities endereco and telephone. When I get the person entity from the bank it should bring all the and phones where the data_exclusao is equal to null .

I use EF and I would like to know where I apply this rule to be generic, ie all database queries always fetch data where the data_exclusao field is equal to null .

Note: I generate the data model through EDMX and the version of EF I use is EF6 .

    
asked by anonymous 01.03.2018 / 16:28

1 answer

0

The way to work around a feature that is not yet available in Entity Farmework 6.2.0 is to use the packages :

With these two packages, the feature is automatically filtered in all SQL of entities configured to run Global filters.

A minimum example:

Entity:

public partial class Funcionario
{
    public int Id { get; set; }
    public string Nome { get; set; }
    public DateTime? DataExclusao { get; set; }
}

How will all SQL work where the Global filter is DataExclusao IS NULL , so to work add namespace :

using Z.EntityFramework.Plus;

In the Contrast of your class that inherits from DbContext , write this line of code:

this.Filter<Funcionario>(x => x.Where(a => a.DataExclusao == null));

Full Code:

public partial class DatabaseContext : DbContext
{
    public DatabaseContext()
        :base(@"Data Source=.\SqlExpress; ...")
    {
        this.Filter<Funcionario>(x => x.Where(a => a.DataExclusao == null));
    }
    public virtual DbSet<Funcionario> Funcionario { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Funcionario>()
            .ToTable("Funcionario");

        modelBuilder.Entity<Funcionario>()
            .Property(e => e.DataExclusao).HasColumnType("datetime");

        modelBuilder.Entity<Funcionario>()
            .Property(e => e.Nome)
                .IsRequired()
                .HasMaxLength(50)
                .IsUnicode(false);
    }
}

After this configuration, instantiate the class and use, for example:

using (DatabaseContext db = new DatabaseContext())
{
    var c = db.Funcionario.ToArray();
}

the SQL that was debugged is as follows:

SELECT 
    [Extent1].[Id] AS [Id], 
    [Extent1].[Nome] AS [Nome], 
    [Extent1].[DataExclusao] AS [DataExclusao]
    FROM [dbo].[Funcionario] AS [Extent1]
    WHERE [Extent1].[DataExclusao] IS NULL

If you do not want to use the filters at some point in your code, use the AsNoFilter() extension method, for example:

var c = db.Funcionario.AsNoFilter().ToArray();

Other examples:

01.03.2018 / 17:42