Fluent NHibernate One-To-Many Mapping

旧街凉风 提交于 2019-12-04 03:54:14
Cole W

You need to change your Advert mapping to cascade:

Id(x => x.Id)
  .GeneratedBy.Identity();

HasMany(x => x.AdvertImages)
  .KeyColumn("AdvertId")
  .Inverse()
  .Cascade.AllDeleteOrphan();

Table("Adverts");

You should then be able to do something like this to persist an Advert object and it's children AdvertImage.

Advert newAdvert = new Advert();
AdvertImage newImage = new AdvertImage();
newImage.Advert = newAdvert;
newAdvert.AdvertImages.Add(newImage);

using(NHibernate.ISession session = SessionFactory.GetCurrentSession())
{
    using (NHibernate.ITransaction tran = session.BeginTransaction())
    {
        session.Save(newAdvert);
        tran.Commit();
    }
}

My entities usually contain Add and Remove methods for bidirectional one to many relationships like this:

public class Advert
{
    public virtual IList<AdvertImage> AdvertImages { get; set; }

    public virtual void AddImage(AdvertImage newImage)
    {
        newImage.Advert = this;
        AdvertImages.Add(newImage);
    }
}

I had the same issue. I spent a while trying all different types of mapping. I then discovered my mappings were fine and it was actually that I needed to wrap my session in a transaction and use the Commit() method after the session.SaveOrUpdate() method.

using(var session = sessionFactory.OpenSession()) 
using(var tx = session.BeginTransaction()) 
{ 
// execute code that uses the session 
tx.Commit(); 
}
Miroslav Popovic

What works for me usually is to set the foreign key column to allow nulls in DB - that would be your AdvertId column, but I'm not sure if that would work in your case, since you are using identity. What NHibernate does is INSERT all with one query and then updates child table foreign key column to the correct id of the parent table. Maybe it would work in your case also.

Here's some similar question that might help: Cascade insert on one-to-many with fluent NHibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!