0

I have a many-to-many relationship with additional table and when I am trying to delete a A object which also has a reference in AB table below error occur:

$exception {"could not delete collection: [A.AB#20][SQL: UPDATE AB SET AId = null WHERE AId = @p0]"} NHibernate.Exceptions.GenericADOException

Cannot insert the value NULL into column 'AId', table 'AB'; column does not allow nulls. UPDATE fails. The statement has been terminated.

My database schema: enter image description here

My classes:

public class A
{
    public virtual int AId { get; protected set; }

    public virtual IList<AB> AB { get; set; }
}

public class B
{
    public virtual int BId { get; protected set; }

    public virtual IList<AB> AB { get; set; }
}

public class AB
{
    public virtual int ABId { get; protected set; }

    public virtual A A { get;  set; }

    public virtual B B { get; set; }

    public virtual int CustomProperty { get; set; }
}

My mappings:

public class AMap : ClassMap<A>
{
    public AMap()
    {
        Table("A");

        SchemaAction.None();

        Id(x => x.AId)
            .GeneratedBy.Identity();

        HasMany(x => x.AB)
            .KeyColumn("AId")
            .Cascade.All();
    }
}

public class BMap : ClassMap<B>
{
    public BMap()
    {
        Table("B");

        SchemaAction.None();

        Id(x => x.BId)
            .GeneratedBy.Identity();

        HasMany(x => x.AB)
            .KeyColumn("BId")
            .Cascade.All();
    }
}

public class ABMap : ClassMap<AB>
{
    public ABMap()
    {
        Table("AB");

        SchemaAction.None();

        Id(x => x.ABId)
            .GeneratedBy.Identity();

        Map(x => x.CustomProperty)
            .Not.Nullable();

        References(x => x.A)
            .Column("AId");

        References(x => x.B)
            .Column("BId")
            .Cascade.None();
    }
}

Code:

_session.BeginTransaction();

var a = _session.Get<A>(1);

foreach (var ab in a.AB) {
    _session.Delete(ab);                 
}

_session.Delete(a);

transaction.Commit();

I want to delete the record in A table and every associated record in AB table.

The simplest solution is to make AId and BId in AB table nullable but I think there is a better solution and it can be resolved in mappings.

Thank you in advance :)

gabrieln
  • 91
  • 3

1 Answers1

0

Try this:

HasMany(x => x.AB)
    .KeyColumn("BId")
    .Cascade.All()
    .Inverse();
core
  • 851
  • 1
  • 8
  • 28