1
votes

There's a ResourcePackage class and a PackageItem class:

public ResourcePackageMap()
{
    DiscriminatorValue((int)ResourceObjectType.Package);

    HasMany(x => x.Children).KeyColumn("AggregationObjectId").Cascade.AllDeleteOrphan();
}

public PackageItemMap()
{
    Id(x => x.Id, "AggregationLinkId");
    References(x => x.ResourceItem, "ChildObjectId");
    References(x => x.Package, "AggregationObjectId");
    Map(x => x.Order, "OrderWithinAggregation");
    Map(x => x.Usage, "Usage");

    Table("tbl_Object_Aggregation_Link");
}

I got an error saying:

could not delete collection: [Domain.ResourcePackage.Children#102c589b-fc1c-451d-8300-a0ef00baa21f][SQL: 
UPDATE tbl_Object_Aggregation_Link SET AggregationObjectId = null WHERE AggregationObjectId = @p0]

NHibernate.Exceptions.GenericADOException: could not delete collection: 
[Domain.ResourcePackage.Children#102c589b-fc1c-451d-8300-a0ef00baa21f]
[SQL: UPDATE tbl_Object_Aggregation_Link SET AggregationObjectId = null WHERE 
AggregationObjectId = @p0] ---> System.Data.SqlClient.SqlException: 
Cannot insert the value NULL into column 'AggregationObjectId', 
table 'KDatabase.dbo.tbl_Object_Aggregation_Link'; 
column does not allow nulls. 
UPDATE fails.  The statement has been terminated.

The relationship table runs as follow:

There's a tbl_Object table and a tbl_Object_Aggregation_Link table, which contains two foreign keys to tbl_Object table.

And the mapping class of tbl_Object_Aggregation_Link table is:

public class PackageItemMap : ClassMap<PackageItem>
{
    public PackageItemMap()
    {
        Id(x => x.Id, "AggregationLinkId");
        References(x => x.ResourceItem, "ChildObjectId");
        References(x => x.Package, "AggregationObjectId");
        Map(x => x.Order, "OrderWithinAggregation");
        Map(x => x.Usage, "Usage");

        Table("tbl_Object_Aggregation_Link");
    }
}
1

1 Answers

0
votes

Either change

       HasMany(x => x.Children).KeyColumn("AggregationObjectId").Cascade.AllDeleteOrphan()

to

       HasMany(x => x.Children).KeyColumn("AggregationObjectId").Cascade.All()

Or make both foreign keys in the 'tbl_Object_Aggregation_Link' table to accept null values.

Edit (Another solution):

judging the map:

References(x => x.Package, "AggregationObjectId");

I can guess you are either passing the property (Package) as null and the database doesn't allow null for this foreign key, or the Id of this package doesn't exist in the database. So either make the column "AggregationObjectId" accept null, or pass a valid package object (you can get it using Nhibernate and pass it), or make the map like this:

 References(x => x.Package, "AggregationObjectId").Cascade.All();

but this will save the package automatically if it couldn't be found it in the database.