FluentNHibernate and primitive type collection

2019-08-09 07:18发布

问题:

I'm having trouble persisting primitive type collection using (Fluent)NHibernate.

Here's the entity and mapping:

public class SomeOne
{
    public virtual long ID { get; set; }
    public virtual string Name { get; set; }
    public virtual string Description { get; set; }
    public virtual Iesi.Collections.Generic.ISet<string> Foo { get; protected set; }

    public SomeOne()
    {
        Foo = new HashedSet<string>();
    }
}


    public SomeOneMap()
    {
        Id(x => x.ID).GeneratedBy.Identity();
        Map(x => x.Name);
        Map(x => x.Description);
        HasMany(x => x.Foo).Element("Code").AsSet().Not.Inverse();
        Table("SomeTypeOne");
    }

However, when I try to save SomeOne instance, associated Foo strings get's ignored.

        var session = factory.OpenSession();
        var one = new SomeOne();
        one.Foo.Add("Dato");
        one.Foo.Add("Mari");
        session.Save(one);

Any idea what could be wrong? Thanks

UPDATE


Here's db schema. it's generated by NH.

回答1:

There are two ways of ensuring your collected is persisted.

  1. Call session.Flush(); after session.Save(one);. This will cause NHibernate to persist your collection. More information on flush can be found here.

  2. Wrap the whole thing in a transaction, i.e.

    using (var session = factory.OpenSession())
    using (var transaction = session.BeginTransaction())
    {
      var one = new SomeOne();
      one.Foo.Add("Dato");
      one.Foo.Add("Mari");
      session.Save(one);
      transaction.Commit();
    }
    

There are several reasons why option two is better than option one. The main advantage is that all objects are saved back to the DB within the same transaction, so if one insert fails then the transaction is rolled back and your DB is not left in an inconsistent state. The acceped answer to this question has an extensive explanation of why you should use transactions with NHibernate.