开发者

ASP.NET MVC: Best practice or design pattern for getting the DTO/EditModel into the Database

I am using AutoMapper to create DTOs for the ViewModel and EditModel. I can't find out a good example of how to take the EditModel and apply the changes it contains to the database.

I first considered using AutoMapper as a two-way mechanism, but it's obviously not recommended: http://www.lostechies.com/blogs/jimmy_bogard/archive/2009开发者_开发知识库/09/17/the-case-for-two-way-mapping-in-automapper.aspx

So, what's the best way (design pattern) for getting a DTO or an EditModel from the Controller to the data store?

UPDATE: based on some of the answers, I should mention that I do use the Repository design pattern and the Entity Framework.

UPDATE: My question is far too subjective, as there isn't a general practice to do this. My conclusion is that a lot of people use AutoMapper both ways even if others don't recommend it.


In it's simplest form, you just need to use AutoMapper to map your model onto your Domain/DTO object, then persist that to your datastore however you do that.

So something that's pretty much out of one of the projects I've done:

Mapper.Map(modelObject, domainObject);
domainObject.Save();
return domainObject.Id;

You might want to return the id out of whatever method you're calling this so you can use it further. It's just a rough example, but that's the basics of it...

EDIT: The line that is: Mapper.Map puts the ViewModel data into the Domain object. From there, the Save() calls whatever you need. In your case, it would be your IRepository.Save() method. For me, that calls into nHibernate's SaveOrUpdate

In my AutoMapper configuration, I have some thing like:

Mapper.CreateMap<OrderDomain, OrderViewDTO>();

and

Mapper.CreateMap<OrderSaveDTO, OrderDomain>();

Does that help?


There are going to be alot of possible answers to your question, too many to list here. That said - I think the thing you want to research next is called an ORM or Object Relational Mapper. Some of the more common options are NHibernate and Entity Framework. This will allow you to take objects in your application and map them to your database.

AutoMapper is a great tool - but I believe the intent is to map between objects (like a view model and an entity).

EDIT: And sense your questions asks about design patterns, I would suggest looking into the Repository pattern - it works well with ASP.NET MVC and there are numerous examples out there.


I use AutoMapper to go both directions. You just need to be sure that you handle any collections yourself when mapping back. AutoMapper works great to flatten a structure but not so well to reconstitute it.


NHibernate is the best way to map your DTO's to your database tables. Entity Framework is not ready for prime time yet, just like ASP.NET MVC. Web Forms with NHibernate is the best way to go.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜