2008-12-16 102 views
3

我有一個使用NHibernate的多對多關係。在NHibernate中刪除多對多關聯

是否有更簡單的方法從所有產品中刪除類別關聯而不爲Join表創建類?

我想的SQL看起來像

DELETE FROM ProductCategories WHERE CategoryId = 123 

,這裏是我們使用刪除協會

 DetachedCriteria fetchCriteria = DetachedCriteria.For<Product>() 
      .CreateAlias("Categories", "categories") 
      .Add(Restrictions.Eq("categories.Id", category.Id)); 

     ICollection<Product> products = productRepo.FindAll(fetchCriteria); 

     foreach(var product in products) 
     { 
      product.Categories.Remove(category); 
      productRepo.Save(product); 
     } 

A產品的代碼一組類別

public class Product{ 
    public ISet<Category> Categories 
    { 
     get;set; 
    } 
} 

一個類別有一個Id Guid屬性

public class Category { 
    public Guid Id {get;set;} 
    public string Name {get;set;} 
} 

非常感謝:O)

回答

3

您是否嘗試過使用ISession.Delete(query)方法?它需要一個HQL查詢,加載對象然後刪除它們。

session.Delete("from Product p join p.Categories c where c.id = :category", category, NHibernateUtil.Entity(typeof(Category))); 

我的HQL是一個但生鏽的,所以如果查詢不是很正確,請原諒。

另一種選擇,如果你不喜歡預加載所有對象的想法,是使用session.CreateSQLQuery,只是傳遞一個直接的SQL語句來執行刪除操作。 NHibernate將執行對服務器沒有問題的問題。