2010-09-05 132 views
0

我想使用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(); 
    } 
} 
+0

抛出什么异常?就硬编码而言,您已经在控制器中对存储库进行了硬编码,因此您的代码与NHibernate紧密结合。捕获一个异常而不用实际做某些事情,比如记录它是非常糟糕的做法。此外,为什么你在'Delete'方法内部创建了一个'BrandRepository'实例,因为它看起来已经是这个类的一部分了? – 2010-09-05 21:53:53

+0

很难弄清楚抛出了哪个异常,因为我必须返回一个视图,否则它不会生成 – 2010-09-05 21:57:27

+0

那么把一个catch(Exception ex)'调试一下'ex'的值是什么,甚至是什么更好地,删除'try/catch'块并保持异常传播。 – 2010-09-05 21:58:11

回答

1

它看起来像Styles属性的映射不正确。你在使用正确的表名吗?从例外情况看,似乎没有这样的表Styles