【问题标题】:Interface -> Entity Mapping接口 -> 实体映射
【发布时间】:2010-03-15 04:54:30
【问题描述】:

假设我有几个这样的定义:

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。

问候, 卡兰

【问题讨论】:

  • 您在将接口(ICategory)映射到表时遇到问题吗?
  • 嘿垫片 - 基本上我收到以下错误“表类别中的关联指的是未映射的类:ICategory”我不确定我是否回答了你的问题。卡兰
  • 刚刚发现了一些可能相关的内容:stackoverflow.com/questions/849664/…

标签: nhibernate entity-framework


【解决方案1】:

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

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

它不是最漂亮的实现,而且感觉很丑,但它确实有效。也许其他人会看到这一点并有替代方案:)。

【讨论】:

  • 这也是我想出的......它可能适用于更简单的属性(如上面的那个),但对于集合来说它绝对不是最佳的。 Entity Framework 4 中是否有更简单的解决方案?
  • 我们对集合使用相同的方法(即:孩子而不是父母)。抱歉,我不知道 EF4。
  • 我有点希望 NHibernate 在这方面的能力更强一些。我正在四处寻找技术上更“合理”的解决方案。感谢您的帮助。
  • Np - 我同意你关于这种气味的看法。我有点希望有人可能会在这里通过我可以采用的更好的解决方案偶然发现您的问题。我自己从来都懒得问这个问题,并接受了我们提出的 hacky 解决方案。
  • 我试图扩展这种方法来处理集合,但我被困在 atm 上。如果接口定义了 ICollection Products,你将如何在具体类中实现 Products?
【解决方案2】:

我不知道关于使用 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 更多的属性,你可以将所有属性放在父 class 元素中,然后只声明你的后续 union -subclass 对象。

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

至于 EF4,我无能为力,因为我从未使用过它。对不起。

【讨论】:

    猜你喜欢
    • 2012-08-31
    • 2012-05-25
    • 2010-09-06
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    • 2017-09-30
    相关资源
    最近更新 更多