Reputation: 265
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
using System.Web.Mvc;
using OnlineStoreApi.Models;
namespace OnlineStoreApi.Controllers
{
public class ProductController : ApiController
{
/*private readonly mystoreEntities1 _myObj = new mystoreEntities1();*/
#region Variables
DataClasses1DataContext _context = new DataClasses1DataContext();
ProductModel products;
#endregion
public IEnumerable<ProductModel> GetALLProducts()
{
var prods = from item in _context.spGetProducts().ToList()
select new ProductModel
{
Id = item.id,
ProductTypeId = item.ProductTypeId,
VendorId = item.VendorId,
OldPrice = item.OldPrice,
Price = item.Price,
ProductCost = item.ProductCost,
PictureId=item.PictureId,
PictureBinary=item.PictureBinary.ToArray(),
MimeType=item.MimeType
};
return prods;
}
public IHttpActionResult GetProduct(int id)
{
products = new ProductModel();
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
}
}
Hi guys, another problem with webapi.I am not able to display details of a product using id. Whenever i type /api/Product/1 all the products are displayed.But the product with id 1 should be displayed. I am not understanding what to do. And another problem is that error occurs in FirstOrDefault method. I dont know why it says ProductModel does not contain definition about FirstOrDefault.
Upvotes: 0
Views: 1278
Reputation: 1
You should create services. dont forget SOLID.
[HttpGet("{id}")]
public ActionResult GetPostById (int id)
{
var result = _postService.GetById(id);
if (result == null)
{
return NotFound();
}
return Ok(result);
}
Upvotes: 0
Reputation:
You calling .FirstOrDefault()
on an instance of ProductModel
which does not implement IEnumerable<T>
. Instead call it on the method which returns the collection
public IHttpActionResult GetProduct(int id)
{
products = new GetALLProducts();
var product = products.FirstOrDefault(p => p.Id == id);
....
Upvotes: 3