using interfaces/abstract classes with Entity Framework CodeFirst
I have an Entity Framework CodeFirst Class (POCO) :
class Contract : IMy开发者_开发问答Contract
{
...
}
interface IMyContract
{
public int DateSigned{get;}
}
why am I not able to intercept context change operations in this way when a Contract is being modified by a client :
void context_SavingChanges(object sender, EventArgs e)
{
foreach (ObjectStateEntry entry in
((ObjectContext)sender).ObjectStateManager.GetObjectStateEntries(
EntityState.Added | EntityState.Modified | EntityState.Deleted))
{
IMyContract myContract = entry.Entity as IMyContract;
if(myContract != null)
{
...
}
}
}
You mentioned Code-first but in the same time you are handling event of ObjectContext
and casting sender to ObjectContext
Try this instead:
public class MyContext : DbContext
{
private static EntityState[] states = new EntityState[]
{
EntityState.Added,
EntityState.Modified,
EntityState.Deleted,
};
...
public override int SaveChanges()
{
// If Entires<IMyContract> doesn't work use Entries() and check type
// inside the loop
foreach(var entry in ChangeTracker.Entries<IMyContract>()
.Where(e => states.Contains(e.State))
{
...
}
}
}
精彩评论