robin
robin

Reputation: 497

Dynamically create an entity instance and add a new entry

Please, consider the following example:

public override int SaveChanges()
{
    foreach (var auditableEntity in ChangeTracker.Entries<ISomething>())
    {
        if (auditableEntity.State == EntityState.Added)
        {
            //Create a new instance of the same entity type. 
            //I don't know which one will be. They just have the same interface.
            var newEntity = ?; //???Reflection???

            //ISomething known properties.
            newEntity.propX = "1";
            newEntity.propY = "2";

            //Invoke Add method.
            ??.Add(newEntity); 
        }
    }

    return base.SaveChanges();
}

I need to dynamically create an instance of all my ISomething entities during SaveChanges() method in order to add a new particular entry on it.

Any help will be very welcome.

Regards

Upvotes: 4

Views: 2646

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205679

You can use the non generic DbContext.Set Method (Type) to get the corresponding non generic DbSet. Then you can use Create method to create a new instance of the same type and Add method to add it.

Something like this:

var entityType = auditableEntity.Entity.GetType();
var dbSet = Set(entityType);
var newEntity = (ISomething)dbSet.Create();

//ISomething known properties.
newEntity.propX = "1";
newEntity.propY = "2";

dbSet.Add(newEntity); 

Upvotes: 3

Related Questions