开发者

ASP.NET MVC, strongly typed view; on edit/update of an item should I map properties or attach object to session?

I'm trying to grasp DDD here, and I've read somewhere that it is possible to reuse the domain entities as viewmodels. I've created a simple CRUD app, but at the U(pdate), I get a bit stuck at "?????":

// snippet of the content of the ItemController:
public ViewResult Edit(Guid id)
{
    Item item = _itemDomainService.GetFromCurrentUser(id);
    return View(item);
}

[HttpPost]
[Transaction]
public ViewResult Edit(Item item)
{
    // Validate here

    //????
    return Redirect("Item", "Details", item.Id);
}

I'm using nhibernate with the session per request pattern ("Transaction" is a custom attribute). But "item" is not "tracked" (it is transient) to the nhibernate session. What is the preferred method of getting the chan开发者_如何学JAVAges in "item" into the corresponding row in the database?

I'm thinking of the folowing options myself:

  • Map all properties to the persistent "item", so (at the "????"):

    var fromDB = _itemDomainService.GetById(item.Id);
    fromDB.Name = item.Name;
    fromDB.Description = item.Description
    // etc
    
  • Attach the item to session:

     // of course session would be abstracted away, but for brevity pretend it gets injected into the controller
     session.Update(item);
    
  • My design is plain wrong, and I need to (for example) not use the session-per request...

What are your thoughts on this?


It is generally considered better form to pass a DTO (Data Transfer Object) between the controller and the view, rather than your domain entities themselves.

Then, in your Edit action in your controller, you retrieve the object from your repository using the Id provided by the DTO, and update the properties, essentially like you suggest above.

e.g.

[HttpPost]
[Transaction]
public ViewResult Edit(ItemDTO item)
{
    // Validate here

    var fromDB = _itemDomainService.GetById(item.Id);
    fromDB.Name = item.Name;
    fromDB.Description = item.Description
    return Redirect("Item", "Details", item.Id);
}

To avoid writing lots of 'fromDB.X = item.X' code, you should have a look at AutoMapper which will map the properties for you if your name your DTO properties according to some simple conventions.


Hmm, tricky because I know MVC but not NHibernate. I do know Entity Framework though so I'll assume they are similar enough for this to still be useful I hope:

I would do something like:

//get the original item from the DB
var fromDB = _itemDomainService.GetById(item.Id);

//update fromDB with values from the current "Item" that was posted
UpdateModel(fromDB);

//then save the changes that were made
_itemDomainService.SaveChanges();
//this last line is how it is done in Entity Framework - but I guess there is something similar in NHibernate
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜