linq mysql database row to array code example

Example: linq mysql database row to array

First make one class having similar attribute as you database table for eg:
        public class Student
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public DateTime DateOfBirth { get; set; }

        }
after that
            List<Student> student = new List<Student>();
            SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Prac\TestAssembly\ForumsProjectCSharp\App_Data\Studetnt.mdf;Integrated Security=True;User Instance=True");
            SqlCommand cmd = new SqlCommand("select * from Student", conn);
            SqlDataReader dr;
            try
            {
                conn.Open();
                dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    student.Add(new Student()
                    {
                        ID = dr.GetInt32(dr.GetOrdinal("ID")),
                        Name = dr.GetString(dr.GetOrdinal("Name")),
                        DateOfBirth = dr.GetDateTime(dr.GetOrdinal("DateOfBirth"))
                    });
                    
                }
                dr.Close();
            }
            catch (Exception exp)
            {

                throw;
            }
            finally
            {
                
                conn.Close();
            }

Tags:

Sql Example