如何删除记录?
我正在尝试使用 ASP.NET MVC、Fluent 和 NHibernate 删除数据库记录。请参阅下面的代码,了解我如何尝试实现此目的的示例。我可以获取、更新和插入记录,但删除不起作用。当在控制器(顶部)中调用 Delete() 方法时,它会抛出异常 (System.Data.SqlClient.SqlException: Invalid object name 'Styles'.
)。
我想避免任何类型的元 SQL 查询,因为如果不需要的话,我不想将表名硬编码到控制器中。
控制器代码段:
// 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;
}
}
存储库代码段:
//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();
}
}
}
映射代码段:
//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();
}
}
I'm trying to delete a database record using ASP.NET MVC, Fluent, and NHibernate. See the code below for examples of how I'm trying to accomplish this. I am able to Get, Update, and Insert records but Delete is not working. When the Delete() method gets called in the controller (top one) it throws an Exception (System.Data.SqlClient.SqlException: Invalid object name 'Styles'.
).
I would like to avoid any sort of meta-SQL query because I don't want to hard code the table name into the controller if I don't have to.
Controller snippet:
// 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;
}
}
Repository snippet:
//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();
}
}
}
Mapping snippet:
//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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来
Styles
属性的映射不正确。您使用的表名是否正确?从异常情况来看,似乎没有这样的表Styles
。It looks like the mapping of the
Styles
property is incorrect. Are you using a correct table name? From the exception it seems that there's no such tableStyles
.