NHibernate:无法删除集合:无法插入值NULL

时间:2012-10-22 04:42:21

标签: c# nhibernate runtime-error

有一个ResourcePackage类和一个PackageItem类:

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");
}

我收到错误说:

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.

关系表如下:

有一个tbl_Object表和一个tbl_Object_Aggregation_Link表,它包含两个tbl_Object表的外键。

tbl_Object_Aggregation_Link表的映射类是:

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 个答案:

答案 0 :(得分:0)

要么改变

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

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

或者    使'tbl_Object_Aggregation_Link'表中的两个外键都接受空值。

编辑(另一种解决方案):

判断地图:

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

我猜你要么将属性(Package)传递为null,并且数据库不允许该外键为null,要么数据库中不存在此包的Id。 因此要么使列"AggregationObjectId"接受null,要么传递一个有效的包对象(你可以使用Nhibernate并传递它),或者像这样制作地图:

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

但如果无法在数据库中找到它,这将自动保存包。