我需要帮助为这种情况创建正确的流畅nh映射:
类别可以是一个或多个类别的子级。因此,导致这个实体:
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
有什么想法吗?
答案 0 :(得分:0)
在查看映射后,我认为您想要更改Cascade选项。这篇文章概述了实体之间的父子关系。虽然它来自拥有孤立实体的观点,但我认为您会发现该博客很有帮助。祝你好运......