Convert DataTable To Generic List Using AsEnumerable In ASP.NET MVC

Sometimes we need to work with a generic list, which will be generated from a model class. Suppose we are getting data from a database in a data table and thinking of binding a view from a model class generic list, then first we need to convert the data table into a generic list .


Related article


So let us see how we can convert a datatable to a generic list using AsEnumerable.
Suppose the model class is EmpModel.cs as below.


public class EmpModel
    {
        [Display(Name = "Id")]
        public int Empid { get; set; }
        [Required(ErrorMessage = "First name is required.")]
        public string Name { get; set; }
        [Required(ErrorMessage = "City is required.")]
        public string City { get; set; }

        [Required(ErrorMessage = "Address is required.")]
        public string Address { get; set; }

    }

The following is the conversion logic


public List<EmpModel> GetAllEmployees()
        {
            connection();
            List<EmpModel> EmpList =new List<EmpModel>();
            SqlCommand com = new SqlCommand("GetEmployees", con);
            com.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(com);
            DataTable dt = new DataTable();
            con.Open();
            da.Fill(dt);
            con.Close();
            //Bind EmpModel generic list using AsEnumerable 
           List<DataRow> list = dt.AsEnumerable().ToList();
            foreach (var item in list)
            {
                EmpList.Add(

                   new EmpModel
                   {
                       Empid = Convert.ToInt32(item["Id"]),
                       Name = Convert.ToString(item["Name"]),
                       City = Convert.ToString(item["City"]),
                       Address = Convert.ToString(item["Address"])

                   });
            }

            return EmpList;

        }


Summary

I hope this article is useful for all readers. If you have any suggestions, then please contact me.

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode