【问题标题】:NHibernate JOIN mapping fails when the mapped field is moved to a base class当映射字段移动到基类时,NHibernate JOIN 映射失败
【发布时间】:2018-10-03 20:27:56
【问题描述】:

有两个具有许多公共字段的模型类,我决定创建一个基类并从它继承它们。

现有的模型类已经带有地图类。

现在在子类中继承的所有公共字段都是虚拟的,以保持 NHibernate 快乐并且它们都映射正常,除了一个......

这是我的情况:

public class BaseClass : EntityBase<Guid>
{
   //This is not complaining 
   public virtual string Text { get; set; }

   //This is complaining
   public virtual Guid TouchGuid { get; set; }
}

public class A : BaseClass
{
    //inherited + specific stuff
}

public class B : BaseClass
{
    //inherited + specific stuff
}

现在这些是映射类:

public class AMap : ClassMapping<A>
{
    //Mapping the ID inherited from EntityBase class
    Id(x => x.Id, mapper =>
    {
        mapper.Generator(Generators.GuidComb);
        mapper.Column("Pk_MenuItemId");
    });

    //Mapping the common field inherited, doesn't complain !
    Property(x => x.Mnemonic);

    //This is the one which is complaining, keep in mind it was working
    //before creating the base class and move the TouchGuid property in it.
    Join("Touch", x =>
    {
        x.Key(k =>
        {
            k.Column("EntityId");
            k.ForeignKey("PK_AClassId");
            k.OnDelete(OnDeleteAction.Cascade);
            k.Unique(true);
        });
        x.Property(p => p.TouchGuid);
    });
}

public class BMap : ClassMapping<B>
{
    //Same map as for class A
}

每当我运行程序,从这些类(表)中加载数据时,都会失败,说它在 A 表和 B 表上找不到 TouchGuid 列,这是错误:

是的,A 表和 B 表之间有公共数据,但我无法更改 db 方案,现在它会增加太多复杂性。

我也需要为基类创建一个表吗?如果可能的话,我想避免创建一个新表。

有什么可能出错的提示吗?

谢谢!

【问题讨论】:

    标签: c# asp.net nhibernate fluent-nhibernate-mapping nhibernate-inheritance


    【解决方案1】:

    我相信 NHibernate 假设数据库模式具有多个表,因为它默认为隐式多态模式。尝试在映射中设置 polymorphism=explicit。

    【讨论】:

    • 好的,我明白了!如果我只有一个孩子,例如只有 A 类,它将完美地工作,但每当我创建第二个孩子时,它都会失败。这对于多态的东西是有意义的,但我没有找到一种方法在流利的 nhibernate 中将其设置为显式,我尝试过 Polymorphism.Explicit();但不幸的是,在当前上下文中不存在多态这个词。您能否添加一些代码来如何在流利的 nhibernate 中将多态性设置为显式?谢谢乔纳斯!
    • 我一直在阅读这方面的内容,似乎只能通过 XML 映射将多态设置为显式,是这样吗?
    • 我认为您使用的是内置的按代码映射,而不是 Fluent NHibernate?
    • 再想一想,您是否尝试过将基类抽象化?
    • 是的,我正在使用代码映射,创建一个继承自 ClassMapping 的类映射,并且在它的构造函数中我拥有所有的映射 Jonas
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多