如何解决NHibernate.NonUniqueObjectException:具有相同标识符值的另一个对象已与会话关联
| 我有财产课[Serializable]
public class MyClass {
public MyClass ()
{
}
public virtual System.DateTime Time {
get;
set;
}
public virtual string Name {
get;
set;
}
public virtual string Department {
get;
set;
}
public virtual string Ip
{
get;
set;
}
public virtual string Address {
get;
set;
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
MyClass t = obj as MyClass ;
if (t == null)
return false;
if (this.Time == t.Time && this.Name== t.Name && this.Department== t.Department)
return true;
else
return false;
}
public override int GetHashCode()
{
int hash = 13;
hash = hash +
(null == this.Time ? 0 : this.Time.GetHashCode());
hash = hash +
(null == this.Name? 0 : this.Name.GetHashCode());
hash = hash +
(null == this.Department ? 0 : this.Department.GetHashCode());
return hash;
}
}
我正在将Nhibernate映射为
<hibernate-mapping xmlns=\"urn:nhibernate-mapping-2.2\" namespace=\"NhibernateTest\" assembly=\"NhibernateTest\">
<class name=\"MyClass\" table=\"NhibernateTest\">
<composite-id>
<key-property column=\"Time\" type=\"DateTime\" name=\"Time\"></key-property>
<key-property name=\"Name\" type=\"string\" column=\"Name\" ></key-property>
<key-property name=\"Department\" type=\"string\" column=\"Department\" ></key-property>
</composite-id>
<property column=\"Ip\" type=\"string\" name=\"Ip\" />
<property column=\"Address\" type=\"string\" name=\"Address\" />
</class>
</hibernate-mapping>
我正在尝试使用复合键对大约40k数据执行批量上传。使用以下代码。
public void StoreInRDBMS(List<MyClass> FileList)
{
ITransaction transaction = null;
try
{
var stopwatch = new Stopwatch();
stopwatch.Start();
ISession session = OpenSession();
using (transaction = session.BeginTransaction())
{
foreach (var File in FileList)
{
session.SaveOrUpdate(File);
}
session.Flush();
session.Clear();
transaction.Commit();
}
session.Close();
stopwatch.Stop();
var time = stopwatch.Elapsed;
}
catch (Exception ex)
{
transaction.Rollback();
}
}
但问题是,在循环中进行迭代时,列表中的第二条记录会引发此错误
{\“具有相同标识符值的另一个对象已与会话NhibernateTest.MyClass关联,实体:NhibernateTest.MyClass \”}
尽管记录是唯一的。并且如果根本不是,也应该更新相同的内容。
如果我在循环中的每次迭代后刷新会话,它将起作用
foreach (var File in FileList)
{
session.SaveOrUpdate(File);
session.Flush();
session.Clear();
}
如果不是通过上述方法完成的话,甚至40分钟记录的通话时间都不会超过17分钟。
有人可以帮忙吗?
解决方法
也许?
foreach (var File in FileList)
{
session.SaveOrUpdate(File);
session.ExecuteUpdate();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。