NHibernate ComponentAsId()实际上并没有设置Id属性

时间:2011-12-30 04:18:08

标签: nhibernate nhibernate-mapping

我正在尝试使用编码映射设置NHibernate(3.2.0.4000),但我无法使ComponentAsId正常工作。

我有一个数据库架构,我无法更改主键由字符串和日期组成的位置,因此我需要使用组件作为Id:

数据库架构

Id varchar(20) NOT NULL,
EffectiveDate datetime NOT NULL,
Property1 int

public class EffectiveDateId
{
    public string Id { get; set; }
    public DateTimeOffset EffectiveDate { get; set; }
}
public class MyClass
{
    public EffectiveDateId Identity { get; set; }
    public int Property1 { get; set; }
}

映射

var mapper = new ConventionModelMapper();

mapper.Class<MyClass>(map => map.ComponentAsId(id => id.Identity, cid =>
{
    cid.Property(x => x.Id, x => x.Length(20));
    cid.Property(x => x.EffectiveDate);
}));

但这不起作用,因为MyClass上的身份属性为空。

XML映射如下所示:

<hibernate-mapping xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:nhibernate-mapping-2.2">
    <class name="Test.MyClass, Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
        <composite-id class="EffectiveDateId, Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
            <key-property name="Id" type="AnsiString" length="20" />
            <key-property name="EffectiveDate" />
        </composite-id>
        <property name="Property1" />
    </class>
</hibernate-mapping>

但是,如果我手动更改XML以包含 name =“Identity”,请执行以下操作:

<hibernate-mapping xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:nhibernate-mapping-2.2">
    <class name="Test.MyClass, Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
        <composite-id name="Identity" class="EffectiveDateId, Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
            <key-property name="Id" type="AnsiString" length="20" />
            <key-property name="EffectiveDate" />
        </composite-id>
        <property name="Property1" />
    </class>
</hibernate-mapping>

它有效。

我尝试通过添加(除了ComponentAsId映射)来设置id

mapper.Class<MyClass>(map => map.Id(id => id.Identity));

但这只会生成一个NHibernate.MappingException

  

Test.MyClass id的模糊映射。定义了带有生成器的id属性,并且您尝试将属性“Identity”的组件Test.EffectiveDateId映射为Test.MyClass的id。

使用调试器我可以看到,对于代码映射配置,ClassMapping.IdentifierProperty为null,而在XML配置中,它设置为NHibernate.Mapping.Property实例。

那么,ComponentAsId()的实现中是否存在未设置IdentifierProperty的错误,或者我做错了吗?

的问候, 埃蒙

0 个答案:

没有答案
相关问题