删除时显示相关实体

时间:2013-05-14 17:24:02

标签: c# hibernate nhibernate cascade

我有一个模型,其中一些关系映射到NHibernate并且它工作正常,样本:

public class A
{
   public int Id { get; set; }
   // other properties

   public ICollection<B> BList { get; set; }
   public ICollection<C> CList { get; set; }
   public ICollection<D> DList { get; set; }
}

此类实体的持久性和读取效果非常好,但当用户删除A实体时, 我想告诉他有一个或多个实体相关(不是什么实体(id,名称等等),但实体的类型),样本:

You cannot delete this register because there are relations with:

-B
-D

(如果是A个实体,有B个或D个关系,而不是C个。)

我知道我可以按实体获取此信息检查实体,但我希望有一个通用解决方案,有什么办法吗?!

1 个答案:

答案 0 :(得分:1)

NHibernate有自己的元数据API,它允许您读取所有映射信息,包括哪些集合映射到属性,以及哪些属性类型。 从每个属性的类型,您可以找到相关类型的名称。

A instance = ...
var metaData = this.session.SessionFactory.GetClassMetadata(instance.GetType());
foreach(IType propertyType in metaData.PropertyTypes)
{
  if(propertyType.IsCollectionType)
  {
    var name = propertyType.Name;
    var collectionType = (NHibernate.Type.CollectionType)propertyType;
    var collection = collectionType.GetElementsCollection(instance);
    bool hasAny = collection.Count > 0;
  }
}
相关问题