سؤال

I'm having a problem trying to get a many to many relationship to save the join record in NHibernate using Automapper in Fluent NHibernate.

There are quite a few other posts about this on S.O but so far none of them have solved the problem, wondering if I'm doing something different some how.

I have the app setup to map, and when i manually create the join record in the DB i do get back the data, so on a read level it is mapping correctly, but it won't persist the relationship.

Here's the relevant mapping. I was using automapper with default conventions but eventually tried this based on another SO post.

.Mappings(m => {
                        m.AutoMappings.Add(AutoMap.AssemblyOf<User>);
                        m.AutoMappings.Add(AutoMap.AssemblyOf<PostalCode>);
                        m.AutoMappings.Add(
                                AutoMap.AssemblyOf<VPA>()
                                    .Override<VPA>(v => 
                                        v.HasManyToMany(x => x.PostalCodes)
                                            .Table("PostalCodesToVPAs")
                                            .ParentKeyColumn("PostalCode_Id")
                                            .ChildKeyColumn("VPA_Id")
                                            .Cascade.SaveUpdate())
                                    .Override<PostalCode>(p => 
                                        p.HasManyToMany(x => x.VPAs)
                                            .Table("PostalCodesToVPAs")
                                            .ParentKeyColumn("VPA_Id")
                                            .ChildKeyColumn("PostalCode_Id")
                                            .Cascade.SaveUpdate().Inverse())
                            );
                    })

My actually save looks like this. It may be overkill as i'm explicitly saving both postal code and vpa but i read a lot about people having problems with the inverse line in the mapping so i wanted to try both. It didn't work.

var postalCode = new PostalCode {Value ="90210", CreatedBy = 0, CreationDate = DateTime.Now, ModifiedBy = 0, ModifiedDate = DateTime.Now};
vpa.PostalCodes.Add(postalCode);
postalCode.VPAs.Add(vpa);
PostalCodeService.Save(postalCode);
VPAService.Save(vpa);

under the covers the service.save calls do

return (int)Session.Save(obj);

Has anyone seen this and know why it wouldn't save the join record?

هل كانت مفيدة؟

المحلول

Figured out the solution, wanted to update in case anyone runs into the same problem.

You have to wrap the save call in a transaction or it doesn't commit the join record. I ended up modifying that service code to read

using (var tx = Session.BeginTransaction()) {
    Session.Save(obj)
    tx.commit();
    return obj.Id;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top