我有一个带属性的类
[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分钟。 任何人都可以提供帮助。
答案 0 :(得分:0)
也许?
foreach (var File in FileList)
{
session.SaveOrUpdate(File);
session.ExecuteUpdate();
}