Take the 2-minute tour ×

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 and the version of NHibernate is

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

it is because the default column is typename + id for the reference which happens to be the same name as the id column. Explicitly state it in the reference.

References(n => n.Parent, "ParentId").LazyLoad().Nullable();

Update: as convention

public class ReferenceColumnConvention : IReferenceConvention
    public void Apply(IManyToOneInstance instance)
        // uncomment if needed
        //if (instance.EntityType == instance.Property.PropertyType)
        instance.Column(instance.Name + "id");
share|improve this answer
Thanks, Firo. That fixed the problem, and it actually makes sense. –  Hendrik W. Hansen Mar 5 '12 at 21:51
Would it by the way be possible to make a convention handling this: If the type of the property is the same as the hosting type, then it should fall back to propertyname + id? That would be useful in most cases I think. –  Hendrik W. Hansen Mar 5 '12 at 22:02
add comment

Your Answer


