我正在使用“wcf 数据服务工具包”进行 CURD 操作。获取/添加/删除工作正常,但更新失败。
在更新的情况下,我看到“GetOne()”方法被调用,但 Save() 没有被调用。
服务代码:
public class UserService : ODataService<UserContext>
{
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
}
}
存储库代码:
public User GetOne(string id)
{
return _session.Query<User>().Where(a => a.Id == int.Parse(id)).SingleOrDefault();
}
public void Save(User u)
{
_session.Store(u);
_session.SaveChanges();
}
数据上下文代码:
public class UserContext : ODataContext
{
public IQueryable<User> Users
{
get { return base.CreateQuery<User>(); }
}
public override object RepositoryFor(string fullTypeName)
{
return new UserRepository();
}
}
型号代码:
[DataServiceKey("Id")]
public class User
{
public int Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string UserEmailAddress { get; set; }
}
这是我的测试用例:
[TestMethod]
public void TestUpdateUser()
{
var context = new UserService.UserContext(new Uri("http://localhost:59050/UserService.svc"));
var user = context.Users.Where(a => a.Id == 385).SingleOrDefault();
user.UserEmailAddress = "updated@email.com";
context.UpdateObject(user);
context.SaveChanges();
var context2 = new UserService.UserContext(new Uri("http://localhost:59050/UserService.svc"));
var updated = context.Users.Where(a => a.Id == 385).SingleOrDefault();
Assert.AreEqual("updated@email.com", updated.UserEmailAddress)
}