converting DataTable to List (ProjectDracula)

前端 未结 2 784
时光说笑
时光说笑 2020-12-21 11:38

I need a static method to convert DataTables(dynamic) to List(again dynamic Entity) here is my code help would be appereciated

        public static ICollect         


        
相关标签:
2条回答
  • 2020-12-21 12:24

    So basically you want use this structure for your mvc .net core app with dependency injection and ado.net for orm The problem that was first initiated this question was when using ado.net you have to map data table to c# object manually.But in extends of years it got grown and now you can easily implement this structure on your application which is dapper like functionality.I grant this is a small sized.But I think this is the fastest way you can actually get results from sql server.Personally you might use dapper which I also suggest to do.It is nice peace of code which I think deserve to go to wiki for future references

    You start with repository which has db context factory injected into it. I used factory pattern for db context because you might want to use multiple instances of sql server on your application. Then factory pattern will be needed. I suggest create a small db for you basic information and make that factory singleton. In this manner a lot of time and effort of fetching data would be eliminated in the first place. In the first method of repo there is example functionality to showcase the design you so you use factory to fetch the result and cast it as object by covert data table function which was provided in previous answer(thank you very much @Nikhil Vartak) .So you have it!. In the further of the post I included convert data table functions to this post and which was main reason of this question. Others are parts of normal .net core or .net normality which is not concern of this post

            /* repo */    
                       public class repo
                           {
                              private readonly IDBContextFactory dBContextFactory; 
                              public repo(IDBContextFactory _dbContextFactory) 
                              {
                                   _dbContextFactory=dBContextFactory;
                              }
                              public string GetLastRecord()
                              {  
      List< Student > studentDetails = new List<Student>();  
        studentDetails = ConvertDataTable<Student>(_dbCtextFactory.Select("mydb","select * from StudentDetail");
            /*refrence from this post https://stackoverflow.com/questions/33515552/converting-datatable-to-listentity-projectdracula */;
    
                              }
                           }
    
            /* interface of repo */
                           public interface IRepo
                           { 
                              public string GetLastRecord();
                           }
    /* controller */
                   public class mycontroller:BaseController
                        {  
                           private readonly IRepo repo;
    
                       public mycontroller(IRepo _repo)
                       {
                         _repo=repo;
                       }
                       [httpGet]
                       public IActionResult<string> GetLastRecord()
                       {
                         return _repo.GetLastRecord();
                       }
                    }
    
    
            /* some factory pattern for db context (multiple dbs) */
                           public class DBContextFactory
                           {
                               private SqlCommand BuildFactory(string dbName)
                               { 
                                    switch(dbName)
                                    {
                                        case 'mydb':
                                          return CreateMyDB();
                                    }
                               }
                               private SqlCommand CreateMyDB()
                               { 
                                  string connectionString = "your connection string";
                                  SqlConnection connection =
                                    new SqlConnection(connectionString));
    
                                    SqlCommand command = new SqlCommand(connection);
                                    return command.Open();
    
                               }
                               //Private SqlCommand GetMyOpenCommand()
                               public DataTable Select(string dbName,string query)
                               {
    
    
                                       SqlDataAdapter dataAdapter=new SqlDataAdapter();
                                       dataAdapter.SelectCommand=BuildFactory(dbName);
                                      DataTable dt =new DataTable();
                                       dataAdapter.Fill(dt);
                                       con.Close();
                                       return dt;
                               }
    
                           }
            /* factory in dependncy pattern */
                      public inteface IDBContextFactory
                      { 
                         SqlCommand BuildFactory(string dbName);
                         SqlCommand CreateMyDB();
                         DataTable Select(string dbName,string query)
                    }
            /****** HERE IS YOUR GENERIC FILE ******/
            private static List<T> ConvertDataTable<T>(DataTable dt)  
            {  
                List<T> data = new List<T>();  
                foreach (DataRow row in dt.Rows)  
                {  
                    T item = GetItem<T>(row);  
                    data.Add(item);  
                }  
                return data;  
            }
    
            private static T GetItem<T>(DataRow dr)  
            {  
                Type temp = typeof(T);  
                T obj = Activator.CreateInstance<T>();  
    
                foreach (DataColumn column in dr.Table.Columns)  
                {  
                    foreach (PropertyInfo pro in temp.GetProperties())  
                    {  
                        if (pro.Name == column.ColumnName)  
                            pro.SetValue(obj, dr[column.ColumnName], null);  
                        else  
                            continue;  
                    }  
                }  
                return obj;  
            } 
            /***** END OF GENERIC PART *****/
        /* USAGE OF GENERIC */
        List< Student > studentDetails = new List<Student>();  
        studentDetails = ConvertDataTable<Student>(dt);
    
    0 讨论(0)
  • 2020-12-21 12:28
    private static List<T> ConvertDataTable<T>(DataTable dt)  
    {  
        List<T> data = new List<T>();  
        foreach (DataRow row in dt.Rows)  
        {  
            T item = GetItem<T>(row);  
            data.Add(item);  
        }  
        return data;  
    }
    
    private static T GetItem<T>(DataRow dr)  
    {  
        Type temp = typeof(T);  
        T obj = Activator.CreateInstance<T>();  
    
        foreach (DataColumn column in dr.Table.Columns)  
        {  
            foreach (PropertyInfo pro in temp.GetProperties())  
            {  
                if (pro.Name == column.ColumnName)  
                    pro.SetValue(obj, dr[column.ColumnName], null);  
                else  
                    continue;  
            }  
        }  
        return obj;  
    } 
    

    Usage:

    List< Student > studentDetails = new List<Student>();  
    studentDetails = ConvertDataTable<Student>(dt);
    

    Source: http://www.c-sharpcorner.com/UploadFile/ee01e6/different-way-to-convert-datatable-to-list/

    0 讨论(0)
提交回复
热议问题