0

I have this code and it does not work. Does anyone know why?

It did not return any data, but if run the query in SQL Server it returns the data.

using (SqlConnection connection = new SqlConnection(_dbContext.GetConnectionString()))
{
    using (SqlCommand command = new SqlCommand())
    {
        StringBuilder stringQuery = new StringBuilder();
        stringQuery.Append(" SELECT cd_material, ds_material");
        stringQuery.Append(" FROM tbl_materiais");
        stringQuery.Append(" WHERE ds_material like @Name");

        command.Parameters.AddWithValue("@Name", "%" + name + "%");
        command.CommandText = stringQuery.ToString();
        command.CommandType = System.Data.CommandType.Text;
        command.Connection = connection;

        connection.Open();

        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                _product = new ProductSell();
                ((IProduct)_product).ID = reader.GetFieldValue<int>(0);
                ((IProduct)_product).Name = reader.GetFieldValue<string>(1);
                listProduct.ToList<IProduct>().Add(_product);
            }
        }
    }
} 
4
  • 2
    Are you getting any error. Check whether your working SQL is similar to one you are geeting in stringQuery.ToString() Commented Apr 16, 2015 at 13:57
  • 3
    your table is really named tbl_materiais ? Looks like a typo Commented Apr 16, 2015 at 13:59
  • 2
    Ensure that your question contains all information relevant to attempt to answer it. (1) What was the full error message (2) where is it being thrown (3) what is this SQL query that works (4) what does the table schema you are querying look like. Commented Apr 16, 2015 at 14:00
  • This code does not do anything. What do you expect it to do? You return null and you don't save the results of your Add() Commented Apr 16, 2015 at 14:10

2 Answers 2

2

What is listProduct and why do you call its ToList<>()?

listProduct.ToList<IProduct>() returns a new instance of List<IProduct> that is forgotten after this line executes. Calling .Add(_product) on this returned list does not affect listProduct.

Sign up to request clarification or add additional context in comments.

1 Comment

is : IEnumerable listProduct = new List();
0

My problem stay here

while (reader.Read())
        {
         DoSomething();
        }

reader.Read() never is read, my table is simple, have only attributes: cd_material(int), ds_material(varchar). And Exception not are triggered. This query :

SELECT cd_material, ds_material FROM tbl_materiais WHERE ds_material = '%produto%' 

Many rows are returned if in owner database ( sql management)

Comments