gpt4 book ai didi

c# - 分配的字符串 ID 和不同大小写字符的 NHibernate 问题

转载 作者:行者123 更新时间:2023-11-30 17:17:49 24 4
gpt4 key购买 nike

在 NHibernate 上保存具有指定字符串 Id 的实体时出现问题...我尝试用一​​个示例来解释该问题。

好吧,假设在数据库中有一个 ID 为“AAA”的实体,如果我执行此语句

ENTITYTYPE entity = Session.Get<ENTITYTYPE>("AAA");
ENTITYTYPE newentity = new ENTITYTYPE() { Id = "aaa" };

Session.Delete(entity);
Session.Save(newentity);
Session.Flush();

在 Flush NHibernate 上引发异常并显示此消息:“无法将数据库状态与 session 同步”/“违反主键”

区分大小写的 ID 似乎有问题,如果我在“newentity”的 ID 上使用“AAA”,那么它就可以工作,但在我的情况下并不那么容易,我必须找到一个替代解决方案。

如何避免这种异常?你能帮帮我吗?

最佳答案

我不知道它是否足够,但你可以用这样的东西来控制它:

public override bool Equals(object obj)
{
T other = obj as T;
if (other == null)
return false;

// handle the case of comparing two NEW objects
bool otherIsTransient = Equals(other.Id, Guid.Empty);
bool thisIsTransient = Equals(Id, Guid.Empty);
if (otherIsTransient && thisIsTransient)
return ReferenceEquals(other, this);

return other.Id.ToUpper().Equals(Id.ToUpper());
}

在实体比较期间使用 ToUpper() 或 ToLower() 方法,或者您可以使用 String.Compare(stringA,strngB,StringComparison.OrdinalIgnoreCase)。

如果您想要更多控制并且这是您的目标,您可以按照此处所述创建您的自定义 ID 生成器:

http://nhibernate.info/doc/howto/various/creating-a-custom-id-generator-for-nhibernate.html

已更新

您是否尝试过创建自定义 GetIgnoreCase(...)?

我认为也可以通过 loader 标签覆盖实体映射文件中默认 Get 方法生成的 SELECT 语句,如下例:

       ...
<loader query-ref="loadProducts"/>
</class>

<sql-query name="loadProducts">
<return alias="prod" class="Product" />
<![CDATA[
select
ProductID as {prod.ProductID},
UnitPrice as {prod.UnitPrice},
ProductName as {pod.ProductName}
from Products prod
order by ProductID desc
]]>

您可以尝试修改返回大写 ID 的 select 语句。

已更新

经过进一步调查,我认为可以使用拦截器来解决您的问题!

阅读这里:

http://knol.google.com/k/fabio-maulo/nhibernate-chapter-11-interceptors-and/1nr4enxv3dpeq/14#

更多文档在这里:

http://blog.scooletz.com/2011/02/22/nhibernate-interceptor-magic-tricks-pt-5/

像这样:

 public class TestInterceptor
: EmptyInterceptor, IInterceptor
{
private readonly IInterceptor innerInterceptor;

public TestInterceptor(IInterceptor innerInterceptor)
{
this.innerInterceptor = this.innerInterceptor ?? new EmptyInterceptor();
}

public override object GetEntity(string entityName, object id)
{
if (id is string)
id = id.ToString().ToUpper();

return this.innerInterceptor.GetEntity(entityName, id);

}

}

然后像这样流畅地注册:

return Fluently.Configure()
...
.ExposeConfiguration(c =>{c.Interceptor = new TestInterceptor(c.Interceptor ?? new EmptyInterceptor());})
...
.BuildConfiguration();

关于c# - 分配的字符串 ID 和不同大小写字符的 NHibernate 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6191169/

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