将DataTable转换为List <entity>(ProjectDracula)

时间:2015-11-04 06:58:41

标签: c# entity-framework model-view-controller

我需要一个静态方法将DataTables(动态)转换为List(再次动态实体) 这是我的代码 帮助会被赞赏

javac Controller.java
javac ComboBoxTypeMismatch.java
java -cp . ComboBoxTypeMismatch

Exception in thread "JavaFX Application Thread" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
    at Controller$1.toString(Controller.java:14)
    at com.sun.javafx.scene.control.skin.ComboBoxListViewSkin.updateDisplayText(ComboBoxListViewSkin.java:388)
    at com.sun.javafx.scene.control.skin.ComboBoxListViewSkin.access$100(ComboBoxListViewSkin.java:57)
    at com.sun.javafx.scene.control.skin.ComboBoxListViewSkin$2$1.updateItem(ComboBoxListViewSkin.java:425)
    at javafx.scene.control.ListCell.updateItem(ListCell.java:471)

2 个答案:

答案 0 :(得分:2)

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;  
} 

用法:

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

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

答案 1 :(得分:0)

因此,基本上,您希望将这种结构用于具有依赖项注入和ado.net for orm的mvc .net核心应用程序。最初引发此问题的问题是,使用ado.net时,您必须手动将数据表映射到c#对象但是随着时间的流逝,它逐渐发展壮大,现在您可以轻松地在应用程序上实现这种结构,就像精巧的功能一样。我同意这是一个很小的规模,但是我认为这是从sql server实际获取结果的最快方法个人而言,您也可以使用dapper,我也建议这样做。这是一段很好的代码和平感,我认为值得去Wiki作将来的参考

从存储库开始,该存储库已注入数据库上下文工厂。我将工厂模式用于db上下文,因为您可能希望在应用程序上使用sql server的多个实例。然后将需要工厂模式。我建议为您创建一个小的数据库,以供您了解基本信息,并使该工厂单例。以此方式,首先将消除大量的时间和精力来获取数据。在第一种回购方法中,有示例功能可以展示您的设计,因此您可以使用工厂来获取结果,并通过上一个答案中提供的秘密数据表功能将其转换为对象(非常感谢@Nikhil Vartak)。你拥有了它!。在文章的进一步内容中,我将转换数据表函数包括到了这篇文章中,这是这个问题的主要原因。其他则是.net核心或.net正常状态的一部分,这与本帖子无关。

        /* 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);