2010-03-15 150 views
0

假设我有一个像这样一些定义:界面 - >实体映射

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

问候, 卡兰

+0

您是否遇到将接口(ICategory)映射到表的问题? – 2010-03-15 04:57:15

+0

嘿shimms - 基本上我得到以下错误“从表类关联指的是未映射的类:ICategory”我不知道如果我回答你的问题,虽然。 Karan – kidoman 2010-03-15 05:04:23

+0

刚发现一些可能相关的东西:http://stackoverflow.com/questions/849664/fluent-nhibernate-how-do-i-map-an-entity-with-a-property-whos-type- is-an-interf – kidoman 2010-03-15 05:08:42

回答

0

NHibernate的有问题映射接口表。

我们已经通过创建用于映射的具体类型的受保护的变量,并暴露所述接口类型作为该具体类型的吸气剂/设定部周围得到:

// 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; 
    } 
} 

(即代码是我的头顶 - 我相信它会有一个语法错误隐藏在其中,但这个想法在那里)。

它不是最漂亮的实现,它感觉很丑,但它的工作原理。也许别人会看到这个,并有一个替代:)。

+0

这也是我想到的......它可能适用于更简单的属性(如上面的那样),但对于集合,它绝对不是最优的。 实体框架4中有更简单的解决方案吗? – kidoman 2010-03-15 05:14:20

+0

我们对集合使用相同的方法(即:儿童而不是父母)。我不知道EF4对不起。 – 2010-03-15 05:15:54

+0

我有点希望NHibernate能在这方面多一点能力。我正在四处寻找更加技术上的“健全”解决方案。 感谢您的帮助。 – kidoman 2010-03-15 05:17:53

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> 

如果你是分类对象类不提供比你的界面ICategory了属性,你可以将所有的父类元素中的属性,则只能声明其后的联合子类其中的对象。

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

至于EF4,我无法提供帮助,因为我从未与之合作过。抱歉。