NHibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session
I have an Class with property
[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;
}
}
I am having my Nhibernate mapping as
<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>
I am trying to perform a bulk upload for some 40k data's with using composite key. using the following code.
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();
}
}
but the problem is , while iterating in the loop the second record in the list throws this error
{"a different object with the same identifier value was already associated with the session: NhibernateTest.MyClass, of entity: NhibernateTest.MyClass"} though the records are unique. and also if at all its not it should update the same.
It works file if I flush the session after every iteration in the loop like
foreach (var File in FileList)
{
session.SaveOrUpdate(File);
开发者_开发问答 session.Flush();
session.Clear();
}
which should not be the case and even its talkin 17 mins for 40 k records if done by above method. Can anybody help regarding the same.
Maybe?
foreach (var File in FileList)
{
session.SaveOrUpdate(File);
session.ExecuteUpdate();
}
精彩评论