I am having a series of issues trying to resolve child entities in my models, I am using nhibernate for persistence, windsor for ioc and automapper for the mapping.
I've attacked this in several ways and almost always get blocked along the way, any help would be greatly appreciated.
My problem for the code below, is that when I try to update the pages layout through the following. (assume only layout-id is changing)
var page = _pageRepository.Get(model.Id);
Mapper.Map(model, page);
using (ITransaction tran = _sessionFactory.BeginTransaction())
{
_pageRepository.Update(page);
tran.Commit();
}
I get a nice error saying,
a different object with the same identifier value was already associated with the session: for the layout model.
Now I have tried: - changing facility to perwebrequest (then says session is closed) - tried remove layout from the cache after getting it (error as above) - i've tried getting the existing session in the resolver (context error)
How should I approach this further? Surely it cant be this hard! Where am I going wrong? Thanks so much.
Here are all the important bits.
I have a model like this:
public class ContentPage : Page
{
public virtual Layout Layout { get; set; }
}
I use a persistent facility to manage my nhibernate sessions like this:
Kernel.Register(
Component.For<ISessionFactory>()
.UsingFactoryMethod(_ => config.BuildSessionFactory()),
Component.For<ISession>()
.UsingFactoryMethod(k => k.Resolve<ISessionFactory>().OpenSession())
.LifestylePerThread() <-- IMPORTANT FOR LATER.
);
And my mapping like this:
CreateMap<BlaViewModel, ContentPage>()
.ForMember(dest => dest.DateModified, src => src.MapFrom(x => DateTime.UtcNow))
.ForMember(x => x.Layout, x => x.ResolveUsing<EntityResolver<Layout>>().FromMember(y => y.Layout_Id));
And finally my resolver like this:
public class EntityResolver<T> : ValueResolver<Guid, T> where T : EntityBase
{
private readonly ISession _session;
public EntityResolver(ISession session)
{
_session = session;
}
protected override T ResolveCore(Guid id)
{
var entity = _session.Get<T>(id);
return entity;
}
}