2010-01-13 68 views
2

我需要在這種場景中創建正確流利的NH映射的幫助:功能NHibernate:多對多自引用映射

類別可以是一個或多個類別的孩子。因此,所得的此實體:

public class Category : Entity, IAggregateRoot 
{ 
    [EntitySignature] 
    public virtual string Name { get; set; } 
    public virtual IList<Category> Parents { get; set; } 
    public virtual IList<Category> Children { get; set; } 
    public virtual IList<ProductCategory> Products { get; set; } 

    public Category() 
    { 
     Parents = new List<Category>(); 
     Children = new List<Category>(); 
     Products = new List<ProductCategory>(); 

    } 

    public virtual void AddCategoryAsParent(Category parent) 
    { 
     if (parent != this && !parent.Parents.Contains(this) && !Parents.Contains(parent)) 
     { 
      Parents.Add(parent); 
      parent.AddCategoryAsChild(this); 
     } 
    } 

    public virtual void RemoveCategoryAsParent(Category parent) 
    { 
     if (Parents.Contains(parent)) 
     { 
      Parents.Remove(parent); 
      parent.RemoveCategoryAsChild(this); 
     } 
    } 

    public virtual void AddCategoryAsChild(Category child) 
    { 
     if(child != this && !child.Children.Contains(this) && !Children.Contains(child)) 
     { 
      Children.Add(child); 
      child.AddCategoryAsParent(this); 
     } 
    } 

    public virtual void RemoveCategoryAsChild(Category child) 
    { 
     if(Children.Contains(child)) 
     { 
      Children.Remove(child); 
      child.RemoveCategoryAsParent(this); 
     } 
    } 
} 

我的初始映射是這樣的:

public class CategoryMap : ClassMap<Category> 
{ 
    public CategoryMap() 
    { 
     Id(p => p.Id).GeneratedBy.Identity(); 

     HasManyToMany(x => x.Parents) 
      .Table("CategoryParents") 
      .ParentKeyColumn("CategoryId") 
      .ChildKeyColumn("ParentCategoryId") 
      .Cascade.SaveUpdate() 
      .LazyLoad() 
      .AsBag(); 

     HasManyToMany(x => x.Children) 
      .Table("CategoryParents") 
      .ParentKeyColumn("ParentCategoryId") 
      .ChildKeyColumn("CategoryId") 
      .Cascade.SaveUpdate() 
      .Inverse() 
      .LazyLoad() 
      .AsBag(); 
    } 
} 

與這個映射的問題是每當我刪除類別作爲父或作爲另一類別的子級,所述得到的SQL語句是這樣的:

NHibernate: DELETE FROM CategoryParents WHERE CategoryId = @p0;@p0 = 2 
NHibernate: INSERT INTO CategoryParents (CategoryId, ParentCategoryId) VALUES (@p0, @p1);@p0 = 2, @p1 = 3 

它首先刪除所有映射,然後插入剩餘的映射。正確的方法是刪除這類聲明的類別父映射:

DELETE FROM CategoryParents WHERE CategoryId = @p0 AND ParentCategoryId = @p1;@p0 = 2, @p1=1 

任何想法?

+1

我注意到你正在使用IAggregateRoot。這是否違背了更多的父母? – Nathan 2010-03-05 05:12:31

回答