我正在尝试让一个使用 RavenDB 的应用程序框架运行起来。我已经设置了一个业务逻辑服务,它与 session 具有 1 对 1 的关系,并有效地成为工作抽象单元。
业务逻辑服务的一部分将包含所有验证。来自服务的方法可能类似于
public void StoreUser(User user)
{
//Some validation logic
if(string.IsNullOrWhiteSpace(user.Name))
throw new Exception("User name can not be empty");
Session.Store(user);
}
问题是,因为一旦存储用户就会被跟踪,我可以绕过对 store 方法的任何验证,但存储正确的值然后稍后更改它
public void TestUserStore()
{
var u1 = new User() {Name = "John"};
var u2 = new User() { Name = "Amy" };
Service.StoreUser(u1);
u1.Name = null; //change is tracked and will persist on the next save changes
Service.StoreUser(u2);
Service.SaveChanges();
//The following fails, as we have stored null as the name rather than "John" bypassing our validation
Assert.IsTrue(Service.AdhocQuery<User>().Any(u => u.Name == "John"));
}
有没有办法让 RavenDB 只存储已存储项目的快照而不跟踪进一步的更改?我是否应该克隆进出业务逻辑服务的所有内容以防止非法更新?或者我在错误的地方进行验证有没有更好的地方来放置这个逻辑?
最佳答案
将您的验证逻辑放在 IDocumentStoreListener
中在每次保存之前,您可以自动进行此类检查。
我写了更多关于这个问题的博客 here .
关于RavenDB 跟踪更改绕过验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12696458/