FluentNHibernate和原始类型集合

FluentNHibernate和原始类型集合

问题描述:

我在使用(Fluent)NHibernate持久化原始类型收集时遇到麻烦.

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

这是实体和映射:

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");
    }

但是,当我尝试保存SomeOne实例时,相关的Foo字符串将被忽略.

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);

有什么主意吗? 谢谢

更新

这是数据库模式.

有两种方法可以确保您收集的数据得以持久保存.

There are two ways of ensuring your collected is persisted.

  1. session.Save(one);之后调用session.Flush();.这将导致NHibernate保留您的收藏集.可以在此处找到更多信息.

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

将整个内容包装在一个交易中,即

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();
}

选项二比选项一更好的原因有很多.主要优点是所有对象都在同一事务中保存回数据库,因此,如果一次插入失败,则事务将回滚,并且数据库不会处于不一致状态.此问题的正确答案解释了为什么应该与NHibernate一起使用事务.

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.