我有两个简单的类,它们作为下面定义的一对多关系相互引用:
public class Project
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<Document> Documents { get; set; }
}
public class Document
{
public virtual int Id { get; set; }
public string FileName { get; set; }
}
我的映射定义为:
public class ProjectMapping : ClassMap<Project>
{
public ProjectMapping()
{
Table("Projects");
Id(x => x.Id).Column("Project_Id").GeneratedBy.TriggerIdentity();
HasMany(x => x.Documents)
.Table("Documents")
.KeyColumn("Document_Project_Id")
.Cascade.AllDeleteOrphan()
.Not.KeyNullable();
Map(x => x.Name).Column("Project_Name");
}
}
public class DocumentMapping : ClassMap<Document>
{
public DocumentMapping()
{
Table("Documents");
Id(x => x.Id).Column("Document_Id").GeneratedBy.TriggerIdentity();
Map(x => x.FileName).Column("Document_File_Name");
}
}
一切似乎都运行良好,添加/更新文档和调用session.Save(项目)反映了我的数据库中的正确更改,但是如果我要从与项目关联的文档列表中删除文档并调用会话。保存(项目)删除的文档永远不会从数据库中删除。
为什么其他一切除了删除之外都有用?
修改 我的MVC 4项目使用Fluent NHibernate设置如下:
public class SessionFactoryHelper
{
public static ISessionFactory CreateSessionFactory()
{
var c = Fluently.Configure();
try
{
//Replace connectionstring and default schema
c.Database(OdbcConfiguration.MyDialect.
ConnectionString(x =>
x.FromConnectionStringWithKey("DBConnect"))
.Driver<NHibernate.Driver.OdbcDriver>()
.Dialect<NHibernate.Dialect.Oracle10gDialect>())
.ExposeConfiguration(cfg => cfg.SetProperty("current_session_context_class", "web"));
c.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Project>());
c.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Document>());
}
catch (Exception ex)
{
Log.WriteLine(ex.ToString());
}
return c.BuildSessionFactory();
}
}
public class MvcApplication : System.Web.HttpApplication
{
public static ISessionFactory SessionFactory { get; private set; }
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
SessionFactory = SessionFactoryHelper.CreateSessionFactory();
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
var session = SessionFactory.OpenSession();
CurrentSessionContext.Bind(session);
}
protected void Application_EndRequest(object sender, EventArgs e)
{
var session = CurrentSessionContext.Unbind(SessionFactory);
session.Dispose();
}
}
我的存储库定义如下:
public class Repository<T> : IRepository<T>
{
public virtual ISession Session
{
get { return MvcApplication.SessionFactory.GetCurrentSession(); }
}
public T FindById(int iId)
{
return Session.Get<T>(iId);
}
public void Save(T obj)
{
using (var transaction = Session.BeginTransaction())
{
try
{
Session.Save(obj);
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
Log.WriteLine(ex.ToString());
}
}
}
public T SaveOrUpdate(T obj)
{
using (var transaction = Session.BeginTransaction())
{
try
{
Session.SaveOrUpdate(obj);
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
Log.WriteLine(ex.ToString());
}
}
return obj;
}
public T Update(T obj)
{
using (var transaction = Session.BeginTransaction())
{
try
{
Session.Update(obj);
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
Log.WriteLine(ex.ToString());
}
}
return obj;
}
}
我在ProjectsController中定义了2个动作,如下所示:
private IRepository<Project> repository;
public ProjectsController()
{
repository = new Repository<Project>();
}
public ActionResult Edit(int iId)
{
Project project = repository.FindById(iId);
if (project == null)
return HttpNotFound();
return View(project);
}
[HttpPost]
public ActionResult Edit(Project project)
{
project = repository.Update(project);
return View(project);
}
如果我要在第一次操作中删除文档(没有HttpPost):
project.Documents.RemoveAt(0);
repository.Update(project);
从数据库中删除正确的行。 但是,如果我在使用HttpPost属性的操作中执行相同操作,则永远不会删除该行。
另外我应该注意,如果我在具有HttpPost属性的操作中向project.Documents添加文档,则repository.Update(project)会成功地将具有正确外键引用的行添加到项目中。这只是在删除文档时失败。
答案 0 :(得分:2)
您是否尝试将.Inverse
添加到HasMany
映射?
另外,我不熟悉Not.KeyNullable
。我觉得这不是必要的。
答案 1 :(得分:2)
级联设置似乎是正确的。提到的问题可能在其他地方:
但是,如果我要从与项目相关联的文档列表中删除文档
怀疑我是会话刷新模式,或者缺少对更新父实体Project
的显式调用,该实体之前是分离的。保证:
首先,调用了Flush()
。如果project
实例仍保留在会话中,,则可以更改刷新的默认行为。 (例如session.FlushMode = FlushMode.Never;
或Commit
没有交易......)
// 1) checking the explicit Flush()
project.Documents.Remove(doc);
Session.Flush(); // this will delete that orphan
第二个可能是被驱逐的project
实例,需要显式更新调用
// 2) updating evicted project instance
project.Documents.Remove(doc);
Session.Update(project);
//Session.Flush(); // Session session.FlushMode = FlushMode.Auto
设置 inverse 在这种情况下(only)帮助减少一次使用UPDATE语句到数据库的行程,重置对doc.Project = null
的引用,然后执行DELETE