1

I have an Entity Framework CodeFirst Class (POCO) :

class Contract : IMyContract
{
   ...
}

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

1 Answer 1

3

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))
        {
           ...
        }
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I'm using this to get to the Context object : var context = ((IObjectContextAdapter)database).ObjectContext; context.SavingChanges += new EventHandler(context_SavingChanges);
the problem lies not with ObjectContext but with the fact that this never evaluates to true : DiscountEntity discountEntity = entry.Entity as DiscountEntity;
And if you debug your application what type of the entity do you see in watch window?
I can't get the WCF Data Service to run in debug mode and to hit breakpoints. really weird. I thought this (WCF Data Service) was the easiest way to expose data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.