界面 - >实体映射

时间:2010-03-15 04:54:31

标签: nhibernate entity-framework

假设我有一些像这样的定义:

public interface ICategory
{
    int ID { get; set; }
    string Name { get; set; }
    ICategory Parent { get; set; }
}

public class Category : ICategory
{
    public virtual int ID { get; set; }
    public virtual string Name { get; set; }
    public virtual ICategory Parent { get; set; }
}

如何在NHibernate / EF 4中映射这样的场景?我正在尝试分离DAL的实现。

我正在学习NHibernate,EF 4。

此致 卡兰

2 个答案:

答案 0 :(得分:0)

NHibernate在将接口映射到表时遇到了问题。

我们通过创建一个用于映射的具体类型的受保护变量,并将接口类型公开为该具体类型的getter / setter来解决它:

// this is mapped to the table
protected virtual Category ConcreteParent { get; set; }

// this is used to access the mapped one
public virtual ICategory Parent 
{ 
    get
    {
        return (ICategory)ConcreteParent;
    } 
    set
    {
        ConcreteParent = (Category)value;
    }
}

(那段代码不在我的脑海中 - 我相信它会隐藏一个语法错误,但这个想法就在那里)。

它不是最漂亮的实现,感觉很丑,但它确实有效。也许其他人会看到这个,并有另一种选择:)。

答案 1 :(得分:0)

我不知道使用NHibernate进行层次结构映射的问题。但是,也许你已经知道如果你报告这个问题,这里应该怎么做:

<class name="ICategory" table="Categories">
  <id name="ID" column="IdCategory">
    <generator class="identity">
  </id>
  <property name="Name"/>
  <component name="Parent" class="ICategory"> <!-- class attribute is normally optional -->
    <!-- Here, I would have some test to do to determine whether we have to list the properties -->
    <!-- I would say no and this would makes sense to me, but without having tested it, I can't confirm. -->
  </component>
  <union-subclass="Category">
    ...
  </union-subclass>
</class>

如果你的Category对象类不再提供比你的接口ICategory更多的属性,你可以将所有属性放在父元素中,然后只声明你后续的 union -subclass 对象。

您可以查询NHibernate Reference Documentation, Chapter 8 - Inheritence mapping以获取有关该主题的更多详细信息。至于组件映射,您要检查Chapter 7 - Component Mapping

对于EF4,我无法帮助,因为我从未使用它。遗憾。

相关问题