2012-06-24 48 views
0

标题几乎总结了我面临的问题。基本上我有2类:使用NHibernate删除一对多关系中的子对象时遇到问题

public class Parent : IIntegerIdentifiable 
{ 
    public virtual long Id { get; set; } 
    public virtual ICollection<Child> Children {get; set; } 
} 

public class Child : IIntegerIdentifiable 
{ 
    public virtual long Id { get; set; } 
    public virtual Parent Parent { get; set; } 
} 

我定义对他们俩的这些classes.The类映射之间的一个一对多的关系是:

public sealed class ParentMap : ClassMap<Parent> 
{ 
    public ParentMap() 
    { 
     Id(x => x.Id).GeneratedBy.HiLo(
      "HiLoUniqueKey", "NextHi", "99", "ObjectType = 'Parent'"); 

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

public sealed class ChildMap : ClassMap<Child> 
{ 
    public ChildMap() 
    { 
     Id(x => x.Id).GeneratedBy.HiLo("HiLoUniqueKey", "NextHi", "99", "ObjectType = 'Child'"); 
     References(x => x.Event).Cascade.All(); 
    } 
} 

因为我想删除所有孩子们从数据库特定的父母,我在ChildRepository写了下面的功能:

public void ClearChildEntries(long parentId) 
    { 
     //I had tried the following and was getting errors before I read the other posts on the topic 
     //QueryOver().Where(x => x.Event.Id == eventId).List().ToList().ForEach(Remove); 
     //Session.flush() 

     //Current code 
     var parent = _parentRepository.GetById(parentId); 
     parent.Children.Clear(); 

     _parentRepository.SaveOrUpdate(parent); 
    } 

我们的代码是设置,使冲洗被调用的请求的结尾。每当我试着执行代码,我得到的错误:

Cannot insert the value NULL into column 'parent_id', table 'test.dbo.Child'; column does not allow nulls. UPDATE fails.

我也试过先删除每个子实体和冲洗会话,然后更新父集合。它给出了同样的错误。问题是 a)为什么nHibernate试图将父id列更新为null然后删除? b)我能做些什么来使删除工作?

只是让你知道我不会浪费你的时间,我的话题提到的其他职位,如
- How to delete child object in NHibernate?
- http://ayende.com/blog/1890/nhibernate-cascades-the-different-between-all-all-delete-orphans-and-save-update
但似乎没有任何工作。有人可以请指点我正确的方向吗?感谢您的帮助!!

回答

相关问题