Session.queryover() 和 session.save() 运行良好。从数据库获取数据或将数据保存到数据库的所有逻辑都运行良好。通过 session.update() 和 session.delete() 对数据库的更改不会反映。没有抛出异常。使用 session.SaveOrUpdate 并没有解决这个问题。这是我的映射
[Serializable]
public class Requirement
{
public virtual int Id { get; set; }
public virtual int CreditRequired { get; set; }
public virtual string Name { get; set; }
public virtual IList<CourseRequirement> CourseRequirements
{
get
{
return new RequirementBC().getCourseRequirement(Id);
}
}
public Requirement()
{ }
public Requirement(DataRow row)
{
Id = int.Parse(row["Id"].ToString());
CreditRequired = int.Parse(row["CreditRequired"].ToString());
Name = row["Name"].ToString();
}
}
public class RequirementMap : ClassMapping<Requirement>
{
public RequirementMap()
{
Table("Requirements");
Id<int>(x => x.Id, m => { m.Column("Id"); m.Generator(Generators.Native); });
Property<int>(x => x.CreditRequired, m => { m.Column("CreditRequired");});
Property<string>(x => x.Name, m => { m.Column("Name"); });
}
}
这是我的逻辑
[Serializable]
public class RequirementBC
{
ISession session = NHibernateHelper.GetCurrentSession();
public void UpdateRequirement(int reqId, string newName, int creditsRequired)
{
session.BeginTransaction();
var req = session.QueryOver<Requirement>().Where(x => x.Id == reqId).SingleOrDefault<Requirement>();
var old = session.QueryOver<Requirement>().Where(x => x.Name == newName && x.Id != reqId).SingleOrDefault<Requirement>();
if (old != null)
throw new Exception("Requirement with that name already exists");
req.Name = newName;
req.CreditRequired = creditsRequired;
session.Update(req);
session.Flush();
session.Transaction.Commit();
}
}
获取当前会话的逻辑
public static ISession GetCurrentSession()
{
HttpContext context = HttpContext.Current;
ISession currentSession = context.Items[CURRENT_NHIBERNATE_SESSION_KEY] as ISession;
if (currentSession == null)
{
currentSession = sessionFactory.OpenSession();
context.Items[CURRENT_NHIBERNATE_SESSION_KEY] = currentSession;
}
if (currentSession.Connection.State == System.Data.ConnectionState.Closed)
{
currentSession = sessionFactory.OpenSession();
}
if (!currentSession.IsConnected)
{
currentSession = sessionFactory.OpenSession();
}
if (!currentSession.IsOpen)
{
currentSession = sessionFactory.OpenSession();
}
if (currentSession.IsDirty())
{
currentSession.Clear();
}
return currentSession;
}
从我在这个论坛和其他人的搜索中,遇到这种情况的人得到一个或另一个异常,但在我自己的情况下没有抛出异常,这使得问题难以追踪。任何帮助将不胜感激。