I have an application storing a tree structure and is able to generate the database fine, but when inserting I get an exception. I simplified the code to narrow down the problem.
The class to be saved:
public class Node
{
public virtual int NodeId { get; set; }
public virtual string Name { get; set; }
public virtual Node Parent { get; set; }
public virtual IList<Node> Children { get; set; }
}
This is the mapper code:
public sealed class NodeMap : ClassMap<Node>
{
public NodeMap()
{
Id(n => n.NodeId).GeneratedBy.Identity();
Map(n => n.Name);
References(n => n.Parent).LazyLoad().Nullable();
HasMany(n => n.Children).LazyLoad().KeyColumn("ParentId");
}
}
When I do an insert like dataClient.Insert(new Node { Name = "Test" }); I get an exception saying:
NHibernate.Exceptions.GenericADOException: could not insert: [Model.Node][SQL: INSERT INTO [Node] (Name, NodeId) VALUES (?, ?); select SCOPE_IDENTITY()]
And the inner exception says:
System.Data.SqlClient.SqlException: Cannot insert explicit value for identity column in table ‘Node’ when IDENTITY_INSERT is set to OFF.
Which is actually perfectly understandable, but I just wonder why it is trying to set an explicit value for NodeId. When I remove the References part, the insert goes through, so it must be related to that somehow.
The version of FluentNHibernate is 1.2.0.712 and the version of NHibernate is 3.1.0.4000.
it is because the default column is
typename + idfor the reference which happens to be the same name as the id column. Explicitly state it in the reference.Update: as convention