gpt4 book ai didi

c# - 如何在(流利的)NHibernate 中使用字符串键

转载 作者:太空狗 更新时间:2023-10-29 22:19:57 24 4
gpt4 key购买 nike

我正在使用使用字符串作为主键的棕地数据库。将 Fluent NHibernateSqlite(用于单元测试的内存提供程序)和 SQL Server 2005 结合使用。

我有以下实体:

public class Entity
{
public virtual DateTime TimeStamp { get; set; }

public virtual string Name { get; set; }
}

有了这个映射:

public class EntityMap : ClassMap<Entity>
{
public EntityMap()
{
Map(_ => _.TimeStamp);
Id(_ => _.Name).CustomType("AnsiString");
}
}

但是,说 NHibernate.TypeMismatchException : Provided id of the wrong type 是行不通的。预期:System.Int32,得到 System.String

如何让它发挥作用?另外,是否有关于 fluent nhibernate 的任何好的文档可用?

提前致谢。

最佳答案

如果你使用字符串作为你的主键,你可能需要做这样的事情:

public class EntityMap : ClassMap<Entity>
{
public EntityMap()
{
Id(x => x.Name).GeneratedBy.Assigned();
Map(x => x.TimeStamp);
}
}

来自 nhibernate 文档:

5.1.4.7. Assigned Identifiers

If you want the application to assign identifiers (as opposed to having NHibernate generate them), you may use the assigned generator. This special generator will use the identifier value already assigned to the object's identifier property. Be very careful when using this feature to assign keys with business meaning (almost always a terrible design decision).

Due to its inherent nature, entities that use this generator cannot be saved via the ISession's SaveOrUpdate() method. Instead you have to explicitly specify to NHibernate if the object should be saved or updated by calling either the Save() or Update() method of the ISession.

这里还有一篇相关文章。它有点过时但仍然适用于您的情况:

http://groups.google.com/group/fluent-nhibernate/browse_thread/thread/6c9620b7c5bb7ca8

关于c# - 如何在(流利的)NHibernate 中使用字符串键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9693943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com