jeudi 8 juillet 2021

How could I alter my code so that I am dynamically adding entities to my database using Entity Framework?

I have a method where I take in an object which consists of multiple properties that each relate to tables in my database. What I currently am doing is using a foreach loop for each table object collection and adding them to my database. However, how can I alter this method so that I am able to dynamically add each object and not explicitly include each type that I need to add to? I am using EntityFrameworkCore(5.0.3).

void Add(RootObject obj)
{
    // Entity Framework database context.
    DbContext context = new DbContext();
    
    // TypeACollection is a Collection<TypeA> object.
    foreach (TypeA a in obj.TypeACollection)
    {
        // Adds the TypeA object to the DbSet<TypeA> that exists in my database context class.
        context.TypeAs.Add(a);
    }

    foreach (TypeB b in obj.TypeBCollection)
    {
        context.TypeBs.Add(b);
    }
   
    foreach (TypeC c in obj.TypeCCollection)
    {
        context.TypeCs.Add(a);
    }

    context.SaveChanges();
}




Aucun commentaire:

Enregistrer un commentaire