我正在编写一个通过代码使用NHibernate映射的应用程序。当我将TimeSpan映射为实体的属性时,TimeSpan被正确映射。
但是,如果我将TimeSpan放在组件映射(值对象)中,我会得到一个异常“操作数类型冲突:bigint与时间不兼容” - 即使我确定我使用TimeSpan映射映射TimeSpan。
以下代码将正确保存时间跨度(例如'1753-01-01T08:00:00')
public class MyEntity
{
public virtual int Id { get; protected set; }
public virtual ISet<AnotherEntity> OtherEntities { get; protected set; }
}
public class AnotherEntity
{
public virtual int Id { get; protected set; }
public virtual TimeSpan MyTimeSpan { get; protected set; }
}
public class MyEntityMap : ClassMapping<MyEntity>
{
public MyEntityMap()
{
Table("MyEntityTable");
Id(x => x.Id, map =>
{
map.Column("Id");
});
Set(x => x.OtherEntities, c =>
{
c.Table("OtherEntityTable");
c.Inverse(true);
c.Key(k => k.Column("MyEntityId"));
}, r => r.OneToMany(m =>
{
m.NotFound(NotFoundMode.Exception);
m.Class(typeof(AnotherEntity));
}));
}
}
public class AnotherEntityMap : ClassMapping<AnotherEntity>
{
public AnotherEntityMap()
{
Table("AnotherEntityTable");
Id(x => x.Id, map =>
{
map.Column("AnotherEntityId");
});
Property(x => x.MyTimeSpan, m => m.Type<TimeAsTimeSpanType>());
}
}
但是,以下代码将尝试将TimeSpan保存为int(例如288000000000)并抛出异常。 (类似地,当它试图水合嵌套值对象时抛出异常。)
public class MyEntity
{
public virtual int Id { get; protected set; }
public virtual MyValueObject MyValueObject { get; protected set; }
}
public class MyValueObject
{
public virtual ISet<NestedValueObject> NestedValueObjects { get; protected set; }
}
public class NestedValueObject
{
public virtual TimeSpan MyTimeSpan { get; protected set; }
}
public class MyEntityMap : ClassMapping<MyEntity>
{
public MyEntityMap()
{
Table("MyEntityTable");
Id(x => x.Id, map =>
{
map.Column("Id");
});
Component(x => x.MyValueObject, c =>
{
c.Set(x => x.NestedValueObjects, map =>
{
map.Table("NestedValueObjects");
map.Key(k => k.Column("MyEntityId"));
}, r => r.Component(n =>
{
n.Property(x => x.MyTimeSpan, m => m.Type<TimeAsTimeSpanType>());
}));
});
}
}
映射是否有错误?或者NHibernate映射是否存在代码错误?