1

I thought I could use my DbContext with a DomainService just the same way I use it with any MVC app:

public class DatabaseContext : DbContext
{
    public DbSet<User> Users { get; set; }  
}

public class UserDomainService : DomainService
{
    private DatabaseContext db;

    public UserDomainService()
    {
        db = new DatabaseContext();
    }

    public IQueryable<User> GetUsers()
    {
        return db.Users;
    }

    public void UpdateUser(User user)
    {
        db.Users.Attach(user);
    }

    public void DeleteUser(User user)
    {
        db.Users.Remove(user);
    }
}

Thing is that, while the Query works, the Delete and Update operations throw exceptions like:

"The object cannot be deleted because it was not found in the ObjectStateManager."

UPDATED: Solution

So this is what I end up doing. Still not sure if this is the correct way to do it:

public class DatabaseContext : DbContext
{
    public DbSet<User> Users { get; set; }  
    public new Context ObjectContext { get { return base.ObjectContext; } }
}

public class UserDomainService : DomainService
{
    private DatabaseContext db;

    public UserDomainService()
    {
        db = new DatabaseContext();
    }

    public override bool Submit(ChangeSet changeSet)
    {
        bool submitResult = false;

        try
        {
            submitResult = base.Submit(changeSet);
            db.SaveChanges();
        }
        catch
        {
        }

        return submitResult;
    }

    public IQueryable<User> GetUsers()
    {
        return db.Users;
    }

    public void UpdateUser(User user)
    {
        db.Users.Attach(user);

        var stateEntry = db.Context.ObjectStateManager
                                   .GetObjectStateEntry(entity);

        foreach (var propertyName in stateEntry.CurrentValues
                                          .DataRecordInfo.FieldMetadata
                                          .Select(fm => fm.FieldType.Name))
        {
             stateEntry.SetModifiedProperty(propertyName);
        }
    }

    public void DeleteUser(User user)
    {
        db.Users.Attach(user);
        db.Users.Remove(user);
    }
}
Ismael
  • 361
  • 3
  • 9

1 Answers1

1

The issue seems to be associated with the fact that the entity has Detached entity state at the moment it is deleted.
The solution for a similar problem is described here, for example.

Devart
  • 119,203
  • 23
  • 166
  • 186
  • Problem is my User is a POCO class not an EntityObject, so it doesn't know about EntityState. – Ismael Nov 17 '10 at 11:18
  • In case of POCO entities there are several approaches. At first, take a look at this post http://social.msdn.microsoft.com/Forums/en/adonetefx/thread/15d54768-026a-4f86-b6e5-f40d39d9ef03 - here a MSFT member describes a solution. One more useful link: http://msdn.microsoft.com/en-us/library/dd456854.aspx - it is described how to detect changes in POCO entities there. – Devart Nov 17 '10 at 11:27