0

我有一个模型与 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')。

我知道我可以逐个实体地获取这个信息检查实体,但是我想要一个通用的解决方案,有什么办法吗?!

4

1 回答 1

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;
  }
}
于 2013-05-14T20:15:29.913 回答