-3

I am using 3 layer architecture for my project. But for an instance i need to return Object from a method and retrieve the values. Here are my two Models:

public class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public decimal Price { get; set; }
}

public class Item
{
    public Product Products { get; set; }
    public int Quantity { get; set; }
}

and my method is:

public class ProductGateway{

public List<Product> GetProductByProductId(int productId)
    {
        List<Product> productList = new List<Product>();
        SqlConnection connection = new SqlConnection(ConnectionString);
        string query = "SELECT ProductName,cast(Price as decimal(10,2)) as Price FROM   Product  WHERE ProductId='" + productId + "' ";
        SqlCommand command = new SqlCommand(query, connection);
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {              
            Product product = new Product(); 
            product.ProductName = reader["ProductName"].ToString();
            product.Price = (decimal)reader["Price"];
            productList.Add(product);
        }
        return productList;
}
    }

and my Controller:CartController

ProductGateway gateway=new ProductGateway();
public ActionResult BuyProduct( int id)
    {
        if (Session["cart"]==null)
        {
            List<Item> cart= new List<Item>();
            cart.Add(new Item()
            {
                Products = gateway.GetProductByProductId(id),// this line getting an error(no list)
                Quantity = 1
            });
            Session["cart"] = cart;
        }

And my cshtml view:

@{
                    var cart = (List<Item>) Session["cart"];
                }
                @foreach (var item in cart)
                {
                    <tr>
                        <td class="cart_product">
                            <a href="@Url.Action("ProductDetails", "Product", new { id = item.Products.ProductId })">@item.Product.Price </a>// an error occurred on ProductId and Price   

Now problem is that my return type is List the Controller get an error onProducts = gateway.AllProductsByProductId(id) and ask for change Item model as Public List<Product> Products .Thus I want to send Object from GetProductByProductId to avoid error in Cart Controller. Is there any way to solve this issue or i need to change entire codes? I really get confused with this scenario.

My Requirement

1.I need to use product property such as @item.Product.Price in my cshtml view. (Current Error: Cannot resolve symbol Price)

2.So that my gateway should return an Product object rather than list of Porduct(for now gateway return list of products).

3. If it is possible to return Object from gateway(assume gateway return single product for each id) then how could I retrieve that object from Cart Controller

Thanks

  • what is `AllProductsByProductId`? You have shown another method but then you are calling this method. – CodingYoshi Feb 25 '17 at 17:06
  • @CodingYoshi Edited – Ziaul Kabir Fahad Feb 25 '17 at 17:09
  • Why are you returning a `List` from `GetProductByProductId(int productId)`? Do you have multiple products with the same `productId`? I doubt this is the case. Therefore, return one product and then you can use the one product in your view. – CodingYoshi Feb 25 '17 at 17:19
  • I want do so. that reason I want set return type 'Product' from 'List' as it return only single product. But I don't know how could I send single Product from the gateway. @CodingYoshi – Ziaul Kabir Fahad Feb 25 '17 at 17:34
  • The easiest solution is to do this in your gateway: `return productList.First()` and change the signature of the method to return `Product` not `List`. Read [this](http://stackoverflow.com/questions/8702386/how-can-i-return-a-single-value-from-an-sqldatareader) for a better way. – CodingYoshi Feb 25 '17 at 17:42
  • @CodingYoshi thanks you very much. I spent almost two days for this. And its really hard to make anyone understand what I really want. Thanks once again. You saved my life. – Ziaul Kabir Fahad Feb 25 '17 at 17:59
  • I added an answer so others know your question has been answered. I am glad I could help. – CodingYoshi Feb 25 '17 at 18:16

1 Answers1

0

In your comments you indicated that only a single product can exist with a give product Id. In that case, your GetProductByProductId(int productId) should return one product. Make the following changes to the method:

public Product GetProductByProductId(int productId)
{
    // your code

    // Change this part
    if(reader.Read())
    {
        Product product = new Product();
        product.ProductName = reader["ProductName"].ToString();
        product.Price = (decimal)reader["Price"];
        return product;
    }

    // not found so we can return null or whatever you want
    return null;
}

And you should also try using SqlParameter to avoid SQL Injection especially if the parameter is coming from an end user.

Community
  • 1
  • 1
CodingYoshi
  • 25,467
  • 4
  • 62
  • 64