我正在为我的公司开发一个新的 MVC 站点,并且对如何创建从 Domain/POCO 对象到 ViewModel 类的映射 [包含验证] 以及反之亦然感到困惑。这是一个示例。
我的域类 [为了简单起见,我省略了其他属性]:
public partial class Glossary
{
public int Id { get; set; }
public string GlossaryItem { get; set; }
public string Definition { get; set; }
}
我的 MVC 应用程序模型文件夹中的 ViewModel 类[具有相应的验证]:
public class GlossaryModel
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
[Required(ErrorMessage = "Please enter a GlossaryItem")]
public string GlossaryItem { get; set; }
[Required(ErrorMessage = "Please enter a Definition")]
public string Definition { get; set; }
}
我的 DTO 到域模型的 Automapper 配置:
protected override void Configure()
{
CreateMap<GlossaryModel, Glossary>();
//....... etc
}
我的控制器用于编辑项目的操作方法:
public class GlossaryController : Controller
{
IGlossaryRepository _glossaryRepository;
IMappingService _mappingService;
public GlossaryController(IGlossaryRepository glossaryRepository, IMappingService autoMapperMappingService)
{
_glossaryRepository = glossaryRepository;
_mappingService = autoMapperMappingService;
}
// .... etc
[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Edit(GlossaryModel glossaryModel)
{
if (ModelState.IsValid)
{
var glossary = _mappingService.Map<GlossaryModel, Glossary>(glossaryModel);
if (glossaryModel.Id <= 0)
_glossaryRepository.Add(glossary);
else
_glossaryRepository.Edit(glossary);
_glossaryRepository.Save();
TempData["message"] = string.Format("{0} has been saved", glossaryModel.Definition);
return RedirectToAction("All");
}
return View(glossaryModel);
}
//....etc
}
它工作正常,但我的问题是......现在说我需要一个列出所有词汇表项目的操作,例如......
public ActionResult All()
{
var allItems = _glossaryRepository.Glossary;
if (allItems.Count() == 0) return View(new List<GlossaryModel>());
// **The below line is the reverse mapping one**
var allItemsModel = _mappingService.Map<IEnumerable<Glossary>, IEnumerable<GlossaryModel>>(allItems);
return View(allItemsModel);
}
但现在我需要自动映射器从域对象转换为 DTO [从 List(Glossary) 到 List(GlossaryModel)],与 Edit 方法相反,将数据推送到视图。所以我是否再次需要在自动映射器配置中映射相反的绑定......!喜欢
protected override void Configure()
{
CreateMap<GlossaryModel, Glossary>(); // Added before for DTO to Domain object
CreateMap<Glossary, GlossaryModel>();// Added for Domain object to DTO
//....... etc
}
双向绑定是个好设计吗?或者我缺少更好的解决方案,请帮助
谢谢,桑杰