Search code examples
silverlightentity-framework-4.1wcf-ria-services

Changes not saved when using inherited DbContext


I'm using a loosely coupled model between my Silverlight client and my DomainService. I'm using POCO with EF 4.1

I'm not using any of the scaffolding the tooling offers.

The DomainService class is declared as:

public partial class MyDomainService : DbDomainService<MyContext>
{
...
}

in the update method I have the following:

public UpdatePerson(PersonInfo source)
{
    var person = DbContext.People.Find(source.Id);
    person.Name = source.Name;
    DbContext.SaveChanges();
}

But when I manually check the database the change is not saved. However if I modify the code to look like this --- all is fine:

public UpdatePerson(PersonInfo source)
{
    using(var context = GetDbContext())
    {
        var person = context.People.Find(source.Id);
        person.Name = source.Name;
        context.SaveChanges();
    }
}

I suppose I don't mind creating my own local context variable, but I'm curious what's going on under the covers that the first approach doesn't work.


Solution

  • Since you are not using the DomainService the way that it is designed to work you may find it doing several weird things. DbContext.SaveChanges is never supposed to be called by your code, it will get called by the DomainService in the PersistChangeset method after all of the CUD methods in the changeset have been processed.

    The DbContext held by the DomainService has several properties changed. ProxyCreationEnabled, ValidateOnSaveEnabled, AutoDetectChangesEnabled, and LazyLoadingEnabled are all set to false. In your case, since AutoDetectChangesEnabled is set to false just changing the person.Name will not trigger the DbContext to know that there are any changes to person.Name.