mercredi 11 octobre 2023

How can I dynamically register DbSets into DbContext and add a row to the table?

I have too many entities and registering everyone of them is giving me a headache not to mention the load to instantiate the dbcontext. so I tried to dynamically register the dbsets.

To dynamically register DbSets into DbContext I used the article in this link: text I added an extension as a file:

public static class ModelBuilderExtensions
{
    public static void RegisterAllEntities<BaseModel>(this ModelBuilder modelBuilder, params Assembly[] assemblies)
    {
        IEnumerable<Type> types = assemblies.SelectMany(a => a.GetExportedTypes()).Where(c => c.IsClass && !c.IsAbstract && c.IsPublic &&
          typeof(BaseModel).IsAssignableFrom(c));
        foreach (Type type in types)
            modelBuilder.Entity(type);
    }
}

then I made an abstract class called BaseEntity that all my entities implimented.

and inside the ApplicationDbContext I overrode the OnModelCreating method:

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            var entitiesAssemblyInt = typeof(BaseEntity<int>).Assembly;
            var entitiesAssemblyGuid = typeof(BaseEntity<Guid>).Assembly;
            modelBuilder.RegisterAllEntities<BaseEntity<int>>(entitiesAssemblyInt);
            modelBuilder.RegisterAllEntities<BaseEntity<Guid>>(entitiesAssemblyGuid);
        }

it works perfectly in migration but when I want to use the dbcontext in my commandHandler to add a row to my table named client I don't know how to call client from context.

context.Client.Add(client);

doesn't work because I didn't register the dbsets directly into dbcontext and there is no Client in the context.





Aucun commentaire:

Enregistrer un commentaire