我认为我可以将我的DbContext与DomainService一起使用,就像我在任何MVC应用程序中使用它一样:
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);
}
}
问题是,当Query工作时,Delete和Update操作抛出异常,如:
“无法删除该对象,因为在ObjectStateManager中找不到该对象。”
更新:解决方案
所以这就是我最终要做的事情。仍然不确定这是否是正确的方法:
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);
}
}