2010-09-05 134 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