【发布时间】:2012-05-09 13:53:34
【问题描述】:
我有一些关于如何使用 asp.net mvc 的最佳实践来实现 DDD 原则的最佳方式的问题。实际上,我想知道,您是如何进行验证的(在视图模型或模型中)?
我有这个 DomainModel 和 ViewModel:
public class Product {
public int Id { get; protected set; }
public string Name { get; set; }
public decimal Price { get; set; }
public int Stock { get; set; }
public Category Category { get; set; }
public Supplier Supplier { get; set; }
public string Code { get; set; } // it has to be unique
}
public class ProductViewModel {
public int Id { get; set; }
/* other simple properties */
public int IdCategory { get; set; }
public int IdSupplier { get; set; }
public string Code { get; set; }
}
好的。该模型使用 NHibernate 映射并且工作正常。我想知道,是否更好地为 ViewModel 或 DomainModel 创建验证?我的意思是,当我在 asp.net mvc 的操作上收到 ViewModel 时,我会验证它,但是如果我在 viewmodel 上添加业务规则,我不会做错吗?我问这个是因为我知道最好将这些业务验证添加到我的域中,但是我应该在我的帖子上进行两次验证,然后再坚持吗?看看我在 asp.net mvc 上的操作:
[Post]
public ActionResult Update(ProductViewModel viewModel) {
// what kind of validations should I do here?
if (invalid) {
return View(viewModel);
}
// how can I return the errors to my View?
// Is here any best pratice to transform from ViewModel to Domain instance?
Product product = ???
_repository.Save(product);
return RedirectToAction("Index");
}
有人可以通过代码做一个例子吗?
【问题讨论】:
标签: c# asp.net-mvc nhibernate domain-driven-design viewmodel