2009-08-01 93 views
1

如何在C#中使用泛型和反射來實現通用的保存和更新操作?利用here...C# - 通用CRUD操作

一些參考

我已經實現了數據檢索,我沒有太多的時間來學習像NHibernate的/ LINQ /實體Frameowrk等技術爲這一刻。出於某種原因,我需要快速解決此問題。

+1

我令你失望 - 這不是*快速解決方案的問題。 – 2009-08-01 15:58:09

回答

4

我想你會更好地使用ORM - LINQ to SQL,LINQ to Entities,LINQ to nHibernate - 而不是重新創建所有這些。從本質上講,你在這些框架/技術中已經爲你做了什麼建議。我的建議是花一些時間瞭解已經存在的工具,並運用您的創造力爲應用程序增加價值,使用已開發的工具進行平凡的工作。當然,除非您正在尋求實施ORM,因爲現有的ORM不適合您的需求。我懷疑事實並非如此,否則你已經知道如何使用反射來完成你所要求的事情。

+0

PLZ查看更新。 – 2009-08-01 15:52:04

0

使用GenericType

的助手的DbContext
public class ContextHelper<T> : IContextHelper<T> 
    { 
     //Instantiate your own EntityFrameWork DB context here, 
     //Ive called the my EntityFramework Namespace 'EF' and the context is named 'Reporting' 
     private EF.DataContext DbContext = new EF.DataContext(); 
     public bool Insert<T>(T row) where T : class 
     { 
      try 
      { 
       DbContext.Set<T>().Add(row); 
       DbContext.SaveChanges(); 
       return true; 
      } 
      catch(Exception ex) 
      { 
       return false; 
      } 
     } 
     public bool Update<T>(T row) where T : class 
     { 
      try 
      { 
       DbContext.Set<T>().AddOrUpdate(row); 
       DbContext.SaveChanges(); 
       return true; 
      } 
      catch (Exception ex) 
      { 
       return false; 
      } 
     } 
     public bool Delete<T>(T row) where T : class 
     { 
      return Update(row); //Pass an entity with IsActive = false and call update method 
     } 
     public bool AddRows<T>(T[] rows) where T : class 
     { 
      try 
      { 
       DbContext.Set<T>().AddOrUpdate(rows); 
       return true; 
      } 
      catch (Exception ex) 
      { 
       return false; 
      } 
     } 

然後實例並調用這裏的類

public class MainLogicClassExample //Catty out logi operations on objects and update DataBase 
{ 
    public void NewEmailRecipient(EF.EmailRecipient recipient) 
    { 
     // logic operation here 

     EntityToDB(recipient); 
    } 
    public void NewReportRecipient(EF.ReportRecipient recipient) 
    { 
     // logic operation here 

     EntityToDB(recipient); 
    } 
    public void UpdateEmailRecipient(EF.EmailRecipient recipient) 
    { 
     // logic operation here 

     UpdateEntity(recipient); 
    } 

    public void UpdateReportRecipient(EF.ReportRecipient recipient) 
    { 
     // logic operation here 

     UpdateEntity(recipient); 
    } 
    // call generic methods to update DB 
    private void EntityToDB<T>(T entity) where T : class 
    { 
     var context = new ContextHelper<T>(); 
     context.Insert(entity); 
    } 

    private void UpdateEntity<T>(T entity) where T : class 
    { 
     var context = new ContextHelper<T>(); 
     context.Update(entity); 
    } 
} 

我添加了一個DemoProject到GitHub的位置: https://github.com/andyf1ynn/EntityFramwork-Generic-Type-DAL