在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上引发异常,并显示以下消息:"无法将数据库状态与会话同步"/"违反PRIMARY KEY"
区分大小写的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();