【发布时间】:2010-09-05 21:50:33
【问题描述】:
我正在尝试使用 ASP.NET MVC、Fluent 和 NHibernate 删除数据库记录。有关我如何尝试完成此操作的示例,请参见下面的代码。我能够获取、更新和插入记录,但删除不起作用。当在控制器(顶部)中调用 Delete() 方法时,它会引发异常 (System.Data.SqlClient.SqlException: Invalid object name 'Styles'.)。
我想避免任何类型的元 SQL 查询,因为如果我不需要,我不想将表名硬编码到控制器中。
控制器 sn-p:
// POST: /Brand/Delete/5
// Here is the handler in the controller
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
IRepository<Brand> repo = new BrandRepository();
repo.Delete(id);
return RedirectToAction("Index");
}
catch
{
throw;
}
}
存储库 sn-p:
//Here is the repository
//The insert/update/get/etc all work fine
void IRepository<Brand>.Delete(int id)
{
using (ISession session = NHibernateHelper.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
IRepository<Brand> repo = new BrandRepository();
session.Delete(repo.GetById(id));
transaction.Commit();
}
}
}
映射 sn-p:
//And here is the mapping for a Brand
public class BrandMap : ClassMap<Brand>
{
public BrandMap()
{
Table("Brands");
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.Name);
HasMany(x => x.Styles)
.Inverse()
.Cascade.All();
}
}
【问题讨论】:
-
抛出什么异常?就硬编码而言,您已经在控制器中硬编码了一个存储库,因此您的代码与 NHibernate 紧密耦合。捕获异常而不实际使用它,例如记录它是非常糟糕的做法。另外,你到底为什么要在
Delete方法中创建一个新的BrandRepository实例,看起来它已经是此类的一部分? -
很难弄清楚抛出了哪个异常,因为我必须返回一个视图,否则它不会构建
-
好吧,放一个
catch (Exception ex)并调试ex的值是什么,或者更好的是,删除try/catch块并让异常传播。 -
这 3 个代码 sn-ps 是单独的文件。 Stackoverflow 上的格式不能让我很容易地将它们分开。我会尝试编辑它
-
好的,好点。请查看我的编辑
标签: nhibernate asp.net-mvc-2 fluent-nhibernate