当前位置:网站首页>[C] overide can override the virtual method inherited from a higher parent

[C] overide can override the virtual method inherited from a higher parent

2022-06-10 22:10:00 I left my life to work

Inheritance relationships

Three class:

  • public class DbContext
  • public abstract class
  • public class BaseContext

among :
BaseContext : BasicDbContext
BasicDbContext : DbContext

Related methods in three classes

DbContext

        //
        //  Abstract :
        // Override this method to further configure the model that was discovered by convention
        // from the entity types exposed in Microsoft.EntityFrameworkCore.DbSet`1 properties
        // on your derived context. The resulting model may be cached and re-used for subsequent
        // instances of your derived context.
        //
        //  Parameters :
        // modelBuilder:
        // The builder being used to construct the model for this context. Databases (and
        // other extensions) typically define extension methods on this object that allow
        // you to configure aspects of the model that are specific to a given database.
        //
        //  speech :
        // If a model is explicitly set on the options for this context (via Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseModel(Microsoft.EntityFrameworkCore.Metadata.IModel))
        // then this method will not be run.
        protected internal virtual void OnModelCreating(ModelBuilder modelBuilder)
        {
    
        }

BasicDbContext

  protected void OnModelCreating(ModelBuilder modelBuilder, Type type)
  {
    
            Code omitted here ...
           base.OnModelCreating(modelBuilder);
       }
 }

BaseContext
This method overrides OnModelCreating There is only one parameter , That is, the overridden method comes from the parent BasicDbContext The father of DbContext, In order to verify , hold BasicDbContext Of OnModelCreating After the method is renamed , The compiler does not prompt for errors .

 protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
    
     base.OnModelCreating(modelBuilder, typeof(BaseEntity));
     foreach (var entityType in modelBuilder.Model.GetEntityTypes().Where(e => typeof(BaseEntity).IsAssignableFrom(e.ClrType)))
     {
    
         modelBuilder.Entity(entityType.ClrType).Property<int>("IsDeleted");
         var parameter = Expression.Parameter(entityType.ClrType, "e");
         var body = Expression.Equal(
             Expression.Call(typeof(EF), nameof(EF.Property), new[] {
     typeof(int) }, parameter, Expression.Constant("IsDeleted")),
         Expression.Constant(0));
         modelBuilder.Entity(entityType.ClrType).HasQueryFilter(Expression.Lambda(body, parameter));
     }
 }

expand

EF Core Ignore global filter references :
【.Net Core】EntityFramework Core Global filtering (HasQueryFilter)

原网站

版权声明
本文为[I left my life to work]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206102050184236.html