I have an ASP.NET MVC application that uses Fluent NHibernate and AutoMapper. I am primarily using AutoMapper to map my Models to ViewModels and vice versa.
When doing the latter, mapping from my viewmodel back to a model, I am wondering how I can map this to a specific instance from the DB, so when I commit the changes back to the DB (using my NHibernate repository layer, via my service layer), the changes are persisted.
Example:
var advert = Mapper.Map<AdvertViewModel, Advert>(model);
_advertService.UpdateAdvert(advert); // then calls repo which commits current NHibernate trans * Nothing in the DB changes *
If I attempt to commit my NHibernate session, so as to UPDATE this advert in the DB, despite the advert being assigned the correct Key/Id as part of the mapping, I guess because the NHibernate session knows nothing about this advert instance(?) it doesn't write away the changes.
Therefore, I am wondering how to handle this mapping scenario in conjunction with NHibernate?
You could do the following:
// fetch the domain model to update
var domainModelToUpdate = _advertService.Get(viewModel.Id);
// Map the properties that are present in the view model to the domain model
// leaving other properties intact
Mapper.Map<AdvertViewModel, Advert>(viewModel, domainModelToUpdate);
// Update the domain model
_advertService.UpdateAdvert(domainModelToUpdate);
But if the view model already contains everything, you don't need to fetch the domain model before updating. All you have to do is to specify the unsaved-value
on your identity column mapping to so that NHibernate knows whether an instance is transient or not and then use SaveOrUpdate
:
Id(x => x.ID).WithUnsavedValue(0);
or if you are using nullable integers for your identities pass null
.