开发者

EF4 Code Only + Ria Services

开发者 https://www.devze.com 2023-01-25 04:19 出处:网络
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

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);
    }
}


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.

0

精彩评论

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