I have two entities:
public class Group
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
private ICollection<Item> _items = new HashSet<Item>();
public virtual ICollection<Item> Items
{
get { return _items; }
set { _items = value; }
}
}
public class Item
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
I use automapping with the following override:
automapping.Override<Group>(m => m.HasManyToMany(_ => _.Items).AsSet());
I construct a group object and few items adding them to the group object. When I save the group object using session.Save(group) the exception occurs:
NHibernate.TransientObjectException: object references an unsaved transient instance – save the transient instance before flushing. Type: NhResearch.ManyToManyTests+Item, Entity: 0 item1
at NHibernate.Engine.ForeignKeys.GetEntityIdentifierIfNotUnsaved(String entityName, Object entity, ISessionImplementor session)
What am I missing here?
You’re missing a cascade setting.
All – if you want to save update and delete items
AllDeleteOrphan – same as all, but also deletes orphaned items
SaveUpdate – cascade on save or update
Delete – cascade only deleted items
FYI, you’re also likely missing the Table specification and the parent and child key columns.