2012-01-07 19 views
8

我是LINQ to SQL的新手,試圖爲基本的創建,讀取,更新和銷燬創建通用數據訪問對象(DAO) CRUD)方法,以便我可以重用代碼。我成功地創建了一個泛型方法,它將通過使用下面的代碼刪除任何實體,但是,我想知道是否有人知道如何創建泛型方法,該方法將通過所有表上存在的公共Id字段選擇任何實體。如何使用LINQ to SQL創建通用數據訪問對象(DAO)CRUD方法

/// <summary> 
    /// Generic method that deletes an entity of any type using LINQ 
    /// </summary> 
    /// <param name="entity"></param> 
    /// <returns>bool indicating whether or not operation was successful</returns> 
    public bool deleteEntity(Object entity) 
    { 
     try 
     { 
      DomainClassesDataContext db = new DomainClassesDataContext(); 
      db.GetTable(entity.GetType()).Attach(entity); 
      db.GetTable(entity.GetType()).DeleteOnSubmit(entity); 
      db.SubmitChanges(); 
      return true; 
     } 
     catch(Exception ex) 
     { 
      Console.WriteLine(ex.StackTrace); 
      return false; 
     } 
    } 

我敢肯定,同樣的圖案將用於更新工作和接入,並希望對GenericDAO一個通用的方法,將獲取我的任何實體(即客戶,發票,工單等.. )基於實體Id。預先感謝回覆。

回答

15

我認爲你正在尋找Repository Pattern,下面是一個簡單的實現它:

首先,你需要創建一個接口IRepository這樣的:

public interface IRepository<T> where T : class 
{ 
    void Add(T entity); 
    void Delete(T entity); 
    void Update(T entity); 
    IEnumerable<T> All(); 
    ... 
} 

然後:

public class Repository<T> : IRepository<T> 
    where T : class, IEntity 
{ 
    DataContext _db; 
    public Repository() 
    { 
     _db = new DataContext("Database string connection"); 
     _db.DeferredLoadingEnabled = false; 
    } 
    public void Add(T entity) 
    { 
     if (!Exists(entity)) 
      GetTable.InsertOnSubmit(entity); 
     else 
      Update(entity); 
     SaveAll(); 
    } 
    public void Delete(T entity) 
    { 
     GetTable.DeleteOnSubmit(entity); 
     SaveAll(); 
    } 
    public void Update(T entity) 
    { 
     GetTable.Attach(entity, true); 
     SaveAll(); 
    } 
    System.Data.Linq.Table<T> GetTable 
    { 
     get { return _db.GetTable<T>(); } 
    } 
    public IEnumerable<T> All() 
    { 
     return GetTable; 
    } 
} 

Then:

public class CustomerRepository : Repository<Customer> 
{ 
    public ProductRepository() 
     : base() 
    { 
    } 
} 

然後你就可以有這樣的:

Customer newCustomer = new Customer { FistName = "Foo", LastName = "Boo" }; 
_customerRepository.Add(newCustomer); 

哪裏Customer是映射到在.dbml定義你的數據庫的實體。這只是一個開始,詳見以下內容:

+0

非常感謝。這工作完美。我過去只使用Hibernate和Java,並且框架已經到位。現在,我是從頭開始從事項目的唯一開發人員,所以這是我第一次不得不在團隊之外編寫自己的數據訪問層。我希望我有足夠的代表來投票解決這個問題。我是新來的社區,當我的代表更高時,一定會投票。 – Grasshopper 2012-01-07 18:31:39

+0

@AaronMajor Glade幫助和歡迎到stackoverflow,順便說一句:你可以標記答案爲接受,如果你發現它有幫助看到這個:http://stackoverflow.com/faq#howtoask – 2012-01-07 19:17:34

+0

@MahmoudGamal偉大的答案。使用接口是強制性的嗎?我們不能僅僅定義一個單獨的類(Repository),也不能使用控制器的Action方法添加或更新或刪除記錄。謝謝 – User 2015-06-18 07:00:40

相關問題