xlecoustillier
xlecoustillier

Reputation: 16351

How to serialize / deserialize elements lists using Fluent NHibernate mappings?

I'm trying to use Fluent NHibernate mapping to serialize / deserialize data.

Starting from a "root" entity, I use the mapping to build a graph with all the entities linked to that entity. Then I serialize this set of entities.

I've got this mapping (only relevant parts) :

[Serializable]
public class Foo
{
    public virtual IList<Bar> Bars { get; set;}
    public virtual IList<System.Guid> Guids { get; set; }
}

[Serializable]
public class Bar
{
    public virtual Foo Foo { get; set; }
}

public class BarMap : ClassMap<Bar>
{
    References(x => x.Foo, "idFoo").Not.Nullable();
}

public class FooMap : ClassMap<Foo>
{
    HasMany(x => x.Bars).KeyColumn("idFoo");
    HasMany(x => x.Guids).Table("guids").KeyColumn("idFoo").Element("guid").AsBag().Not.LazyLoad();
}

Everything works correctly for Foo and Bar serialization and deserialization. But when trying to persist the deserialized data back in the DB, the Guids list isn't persisted, although its data is found in the Foo object.

I googled around for some time, but didn't find anything useful. I tried with Inverse too, to no avail. I also tried to Cascade.SaveUpdate(), which also didn't work.

Is it because it uses an extra table to store values as Elements ? That's the only specificity about this list I can think of.

What am I missing that prevents this restoration from working ?

Any idea welcome. Thanks.

EDIT:

The Guids list is serialized and deserialized correctly. The only thing that isn't done is the DB insertion of the guids list, but it's present in the deserialized data.

EDIT 2:

The weird part is that another piece of code elsewhere in the project does the same, this time successfully. So maybe is it a obscure NHibernate configuration parameter being different on both sides, but the mainNH.xml.config is the same file each time.

Upvotes: 4

Views: 1221

Answers (4)

Herman Schoenfeld
Herman Schoenfeld

Reputation: 8734

Try

Session.Merge(bar);
Session.Merge(bar.Foo);
Session.SaveUpdate(bar);

Upvotes: 1

Herman Schoenfeld
Herman Schoenfeld

Reputation: 8734

Try flushing your session before you Save, and make sure you Save (not SaveOrUpdate).

Upvotes: 1

Herman Schoenfeld
Herman Schoenfeld

Reputation: 8734

Try adding an Inverse(false) into your HasMany mapping.

Upvotes: 1

Herman Schoenfeld
Herman Schoenfeld

Reputation: 8734

It's likely your Save/Update isn't cascading to child collection.

Change your mapping to

  HasMany(x => x.Guids).Cascade.SaveUpdate().Table("guids").KeyColumn("idFoo").Element("guid").AsBag().Not.LazyLoad();

Upvotes: 1

Related Questions