FluentNHibernate and primitive type collection

北城余情 提交于 2019-12-24 11:37:41

问题


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.



来源:https://stackoverflow.com/questions/15475566/fluentnhibernate-and-primitive-type-collection

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