NHibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: 1, of class: ZhuJi.Modules.CountModule.Domain.CountHour。
public void Insert(int id, string ip, int pvs, int ips, int cookies, string area, string province, string city, int visits, DateTime addTime, string referSite, string referUrl, string os, string browser, string resolution, string respondents)
{
ISession session = NHibernateHelper.GetCurrentSession();
ITransaction tx = null;
try
{
string hql = string.Empty;
tx = session.BeginTransaction();
ZhuJi.Modules.CountModule.Domain.CountHour domainCountHour = new ZhuJi.Modules.CountModule.Domain.CountHour();
hql = string.Format("From CountHour as tmp Where tmp.Ip Like '{0}'",ip,addTime);
IList<ZhuJi.Modules.CountModule.Domain.CountHour> listCountHour = session.CreateQuery(hql).List<ZhuJi.Modules.CountModule.Domain.CountHour>();
if (listCountHour.Count > 0)
{
domainCountHour.Id = listCountHour[0].Id;
domainCountHour.Ip = ip;
domainCountHour.Ips = ips;
domainCountHour.Pvs = listCountHour[0].Pvs + pvs;
domainCountHour.Cookies = listCountHour[0].Cookies + cookies;
session.Refresh(domainCountHour);
session.Update(domainCountHour);
session.Flush();
}
else
{
domainCountHour.Ip = ip;
domainCountHour.Ips = ips;
domainCountHour.Pvs = pvs;
domainCountHour.Cookies = cookies;
domainCountHour.AddTime = addTime;
session.Save(domainCountHour);
session.Flush();
}
tx.Commit();
}
catch (HibernateException ex)
{
if (tx != null) tx.Rollback();
throw ex;
}
finally
{
NHibernateHelper.CloseSession();
}
}
|
我也被这个问题困扰了很久,原因是在同一个Session里面只允许ID相同的对象存在一个实例, 比如你在页面Load的时候 User user = GetUserById(123); 然后在另一个地方,这时Session 还没有关闭, 又使用了一次 User user2 = GetUserById(123);(或者其它方式产生这个对象,比如你这里New了一个出来,设定ID然后再插入) 这时就有问题了. 反正我现在也不用NH了~~~不好用~~要是在构造第二个对象前关闭前一个Session,问题又来了, 大概是这个Session关闭时它里面的对象就不能再生存了~~;( 谁有更好的办法呢. |