سؤال

This is my Class:

public class Customer
   {
      public int ID { get; set; }

      public string Card_ID { get; set; }

      public double Cash { get; set; }

      public string Name { get; set; }

      public Image Photo { get; set; }
   }  

I need to make a SELECT on my database to get some information of the customer, I used to use DataSet but I saw it's not the best choice when it comes to performance. Also I need to read only 2 or 3 fields, I started this method:

public List<Customer> ConsultCustomerData(string cardID)
   {
      list<Customer> customer = null;
      string sql = "SELECT name, cash FROM customers WHERE card_id = @cardID";            
       try
          {
             MySqlCommand cmd = new MySqlCommand();
             cmd.CommandText = sql;
             cmd.CommandType = CommandType.Text;
             cmd.Parameters.Add(new MySqlParameter("@cardID", MySqlDbType.VarChar)).Value = cardID;

           }
        catch (Exception ex)
          {
            throw new Exception(ex.Message);
          }
   }  

Now I don't know how to continue...
How may I return those informations using List or IList ?

هل كانت مفيدة؟

المحلول

You can use command.ExecuteReader method and fill entity data using reader.

 public List<Customer> ConsultCustomerData(string cardID)
 {
    List<Customer> list = new List<Customer>();
    string sql = "SELECT name, cash FROM customers WHERE card_id = @cardID";        

    MySqlCommand cmd = new MySqlCommand();
    cmd.CommandText = sql;
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.Add(new MySqlParameter("@cardID", MySqlDbType.VarChar)).Value = cardID;

    using (IDbDataReader reader = cmd.ExecuteReader()) {
        while (reader.Read()) {
             list.Add(new Customer { 
                 Name = reader.GetString(0), 
                 Cash = reader.GetDouble(1) 
             });
        }
    }

    return list;
} 

Check:

  1. ADO.NET IDbCommand interface and its MySql implementation
  2. ADO.NET IDataReader interface and its MySql implementation

نصائح أخرى

You can create a detareader with your query. Afer initialize youe list. The do while(datareader.read()) and inside your loop create a Customer object giving reader's values and at the end add it to the list.

You can do it the good 'ol fashioned way with cmd.ExecuteReader() or use a nice ORM like Dapper.

public List<Customer> ConsultCustomerData(string cardID)
{
    const string query = "SELECT name, cash FROM customers WHERE card_id = @cardID";
    try
    {
        using(var connection = new MySqlConnection(connectionString))
        {
            connection.Open();
            return connection.Query<Customer>(query, new { cardID }).ToList();
        }
    }
    catch(Exception ex)
    {
        // Logging, etc..
        Console.Write(ex.ToString());
        throw; //Rethrow exception
    }
}

I would definitely push for switching to using an ORM like Entity Framework or even Linq to SQL - However, to answer your question you need to read the information from the query i.e.

using (var reader = cmd.ExecuteReader())
{
    List<Customer> customers = new List<Customer>();
    while(reader.Read())
    {
        customers.Add(new Customer
        {
            Name = reader.GetString(0),
            Cash = reader.GetDouble(1)
        });
    }
    return customers;
}

Use SQL Data Reader for reading the data and set associated data to to your entity and build the list like shown as below.

    list <Customer> lstCustomer =new list <Customer>();
    while (reader.Read())
    {
         Customer cus=new Customer();
         cus.Card_ID =......
            .............
            ................
            lstCustomer.Add(cus);

     }

Add Model.edmx to your project. Then you can easily understand the rest. It creates the model for you. You don't need to worry about creating classes. Also helpful if you have table relationship. You don't have to write SQL code to write or read from database.

Here is the link how to use EF.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top