I've got code in a SavingChanges() event handler for a DbContext base class that all of my DbContext classes extend from. My goal is to send all the data in every database through SavingChanges() and then store the data back into the databases.
Each database has its own DbContext. I've got a program that finds all the DbContexts using a dependency container that relies on all the DbContexts to be bound in their DependencyRegistration files.
The problem is that I can't get all the Types that are managed by each DbContext so that I can do DbContext.Set<Type>().Skip(pageNumber*pageSize).Take(pageSize). I've tried to get the types but the logic I am using only gets the types that were added using DbSet<Type>. However most of the types stored in the databases were setup using mapping classes that extend EntityTypeConfiguration. Here is some code from one of the mapping files:
ToTable("Customers", Schema.Customers);
HasRequired(x => x.Configuration)
.WithRequiredDependent(x => x.Customer)
.WillCascadeOnDelete(true);
Here is what I have tried. The code only found the types set with DbSet<Type> which is only a small percent of each of the databases.
var dbContexts = DependencyContainer.ResolveAll<DbContext>().OrderBy(x => nameof(x)).ToList();
foreach (var dbContext in dbContexts)
{
var dbSetProperties = new List<PropertyInfo>();
var properties = dbContext.GetType().GetProperties();
foreach (var property in properties)
{
var setType = property.PropertyType;
var isDbSet = setType.IsGenericType
&& (typeof(IDbSet<>).IsAssignableFrom(setType.GetGenericTypeDefinition())
|| setType.GetInterface(typeof(IDbSet<>).FullName) != null);
if (isDbSet)
{
dbSetProperties.Add(property);
}
}
foreach (var dbSet in dbSetProperties)
{
Log.Debug($" Type found: {dbSet.Name}");
}
// use dbSetProperties to page through data
// call SaveChanges() to trigger SavingChanges() event handler
}
dbContext.Type.ToList() doesn't work either. If I was using Entity Framework Core then I could do dbContext.Model but that doesn't help in this situation.