NHibernate中的多对一映射不工作

本文关键字:工作 映射 多对一 NHibernate | 更新日期: 2023-09-27 18:15:50

我有以下持久类的例子:

using NHibernate.Mapping.Attributes;
namespace GumiDAL.Domain
{
    [Class]
    public class Foo
    {
        [Id(0)]
        [Generator(1, Class="identity")]
        public virtual int Id { get; set; }
        [Property]
        public virtual string Name { get; set; }
    }
    [Class]
    public class Bar
    {
        [Id(0)]
        [Generator(1, Class = "identity")]
        public virtual int Id { get; set; }

        [ManyToOne(Name="foo")]
        public virtual Foo foo { get; set; }
    }
}

序列化程序集将创建以下xml:

<!--
Generated from NHibernate.Mapping.Attributes on 2015-10-02 13:08:49Z.
-->
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
    <class name="Example.Domain.Foo, ExampleAssembly">
        <id>
            <generator class="identity"/>
        </id>
        <property name="Name"/>
    </class>
    <class name="Example.Domain.Bar, ExampleAssembly">
        <id>
            <generator class="identity"/>
        </id>
        <many-to-one name="foo"/>
    </class>
</hibernate-mapping>

但是当我尝试设置配置时,我得到一个异常,有以下消息和堆栈跟踪:

<>之前无法编译反序列化的映射文档。第一次异常类型'NHibernate。NHibernate.dll中发生了MappingException在NHibernate.Cfg.Configuration。LogAndThrow(异常异常)在c:'Projects' NHibernate -core'src'NHibernate'Cfg'Configuration.cs:line 344在NHibernate.Cfg.Configuration。AddDeserializedMapping(HbmMapping mappingDocument,字符串documentFileName)在c:'Projects' NHibernate -core'src'NHibernate'Cfg'Configuration.cs:行532在NHibernate.Cfg.Configuration。AddValidatedDocument(NamedXmlDocument文档)在c:'Projects' NHibernate -core'src'NHibernate'Cfg'Configuration.cs:第501行在c:'Projects' NHibernate -core'src'NHibernate'Cfg'Configuration.cs:line 1867在NHibernate.Cfg.Configuration。AddDocumentThroughQueue(NamedXmlDocument文档)在c:'Projects' NHibernate -core'src'NHibernate'Cfg'Configuration.cs:line 1858在NHibernate.Cfg.Configuration。AddXmlReader(XmlReader hbmReader,字符串名称)在c:'Projects' NHibernate -core'src'NHibernate'Cfg'Configuration.cs:line 1851在NHibernate.Cfg.Configuration。AddInputStream(流xmlInputStream,字符串名称)在c:'Projects' NHibernate -core'src'NHibernate'Cfg'Configuration.cs:行640在NHibernate.Cfg.Configuration。AddInputStream(流xmlInputStream)在c:'Projects' NHibernate -core'src'NHibernate'Cfg'Configuration.cs:行614在Example.Domain.Tests.SetUp ()之前

对我来说,xml中的一切看起来都是正确的…你知道我错过了什么吗?

NHibernate中的多对一映射不工作

name="" 属性表示c#属性。因此,我们应该使用

// instead of this
<many-to-one name="foo_id"/>
// we need this
<many-to-one name="foo" column="foo_id"/>

因此,属性的名称是foo而不是foo_id。我想我们需要这样的映射:

//[ManyToOne(Name="foo_id")]
[ManyToOne(Column="foo_id")]
public virtual Foo foo { get; set; }

对于全栈异常,这将更容易,但同时,<id>元素的名称应该是:

<id name="Id" column="foo_id"...