Search code examples
nhibernatefluent-nhibernate

NHibernate inserts twice to base class when saving subclass. Violates unique constraint


I am using fluent nhibernate with a legacy oracle db, and Devart Entity Developer to generate mapping and entity classes.

I have a base table Product, which has several subclasses, including Tour. When saving Tour, nhibernate issues 2 identical inserts to the Product table which violates PK unique constraint.

Product mapping is:

public class ProductMap : ClassMap<Product>
{
    public ProductMap()
    {
        Schema("CT_PRODUCTS");
        Table("PRODUCT");
        OptimisticLock.None();
        LazyLoad();
        CompositeId()
            .KeyProperty(x => x.Season, set =>
            {
                set.Type("CT.DomainKernel.Enums.Season,CT.DomainKernel");
                set.ColumnName("SEASON");
                set.Access.Property();
            })
            .KeyProperty(x => x.ProductCode, set =>
            {
                set.ColumnName("PROD_CODE");
                set.Length(10);
                set.Access.Property();
            });
        Map(x => x.Name)
            .Column("NAME")
            .Access.Property()
            .Generated.Never()
            .CustomSqlType("VARCHAR2")
            .Length(200);
        HasOne(x => x.Tour)
            .Class<Tour>()
            .Access.Property()
            .Cascade.SaveUpdate()
            .LazyLoad();
    }
}

Tour mapping is:

public class TourMap : SubclassMap<Tour>
{
    public TourMap()
    {
        Schema("CT_PRODUCTS");
        Table("TOUR");
        LazyLoad();
        KeyColumn("SEASON");
        KeyColumn("PROD_CODE");
        Map(x => x.Duration)
            .Column("DURATION")
            .Access.Property()
            .Generated.Never()
            .CustomSqlType("NUMBER")
            .Not.Nullable()
            .Precision(3);
        HasOne(x => x.Product)
            .Class<Product>()
            .Access.Property()
            .Cascade.SaveUpdate()
            .LazyLoad()
            .Constrained();
    }
}

Tour Entity class:

public partial class Tour2 : Product
{
    public virtual Product Product
    {
        get
        {
            return this._Product;
        }
        set
        {
            this._Product = value;
        }
    }
}

Any Ideas as to what is going wrong?


Solution

  • The solution to this was to Remove the Property references from Tour to Product, and from Product to Tour, which when thought about, make no sense anyway.