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
ISomething, as the concrete type could be anything. Once you've got access to the type, use[Activator.CreateInstance](https://msdn.microsoft.com/en-us/library/wccyzw83(v=vs.110).aspx)and cast the result toISomething.foreachasChangeTracker.Entries().Where(p => p.State == EntityState.Added)instead. ChangeTracker brings the current entity in item.Entity.GetType().Name for example.auditableEntity.Entity.GetType()and construct a new object viaActivator.CreateInstance()(then cast that result back toISomething).