我似乎无法找到一个基本的代码示例,看看TryUpdateModel是如何工作的?你什么时候使用它,为什么?
我无法理解,如何使用TryUpdateModel并同时保存MVC架构.
如果我没有弄错的话,使用datacontexts必须在模型中.所以,这样的代码
var db=new TestEverybody();//it is class, which was generated by EntityFramework
var currentTesting=db.Testing.(t => t.id == id).First();
Run Code Online (Sandbox Code Playgroud)
必须位于模型中,而不是控制器中,不是吗?
但TryUpdateModel用法的示例如下:
public ActionResult Edit(Testing obj)//Testing collection
{
var db = new TestEverybody();
var currentTesting=db.Testing.(t => t.id == obj.id).First();
TryUpdateModel(currentTesting);
db.SaveChanges();
return RedirectToAction("Index");
}
Run Code Online (Sandbox Code Playgroud)
这种方式不会打破MVC架构吗?我们在控制器中使用数据库,而不是在特殊的Model类中.
那么,在真实项目中使用TryUpdateModel的最佳方法是什么?
我目前正在使用AutoMapper将我的Entity Framework实体映射到我的View Model:
public class ProductsController : Controller
{
private IProductRepository productRepository;
public ProductsController(IProductRepository productRepository)
{
this.productRepository = productRepository;
}
public ActionResult Details(int id)
{
var product = productRepository.GetProduct(id);
if( product == null )
return View("NotFound");
ProductDetailsViewModel model = Mapper.Map<Product, ProductDetailsViewModel>(product);
return View(model);
}
}
Run Code Online (Sandbox Code Playgroud)
这很好用.我的问题是当我需要从我的View Model转到我的实体以更新数据库时.我应该使用AutoMapper吗?这是一个糟糕/危险的做法吗?
似乎AutoMapper很适合将复杂类型展平为简单(平面)类型,但到目前为止,我正在努力尝试从平面/简单到更复杂的类型,如我的实体具有各种导航属性.
如果使用AutoMapper执行此操作是个坏主意,那么我的代码对于Create操作会是什么样子?
public ActionResult Create(CreateProductViewModel model)
{
if( ModelState.IsValid )
{
// what do i do here to create my Product entity?
}
}
Run Code Online (Sandbox Code Playgroud)
编辑动作怎么样?
public ActionResult Edit(int id, EditProductViewModel model)
{
Product …Run Code Online (Sandbox Code Playgroud)