开发者

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))
        {
           ...
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜