This can be useful aswell
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using TestUe.Models;
namespace TestUe.Controllers
{
public class stocksController : ApiController
{
private CompanyEntities db = new CompanyEntities();
// GET: api/stocks
public IHttpActionResult Getstocks(int sid)
{
var stocks = db.stocks.Include("products").Where(s => s.store_id == sid).Select(s => new StocksDTO()
{
store_id = s.store_id,
product_id = s.product_id,
quantity = s.quantity,
product_name = s.products.product_name,
});
return Ok(stocks);
}
// GET: api/stocks/5
[ResponseType(typeof(StocksDTO))]
public IHttpActionResult Getonestocks(int sId, int pId)
{
stocks stocks = db.stocks.Find(sId, pId);
StocksDTO stdto = new StocksDTO()
{
store_id = stocks.store_id,
product_id = stocks.product_id,
quantity = stocks.quantity,
product_name = stocks.products.product_name
};
if (stocks == null)
{
return NotFound();
}
return Ok(stdto);
}
// PUT: api/stocks/5
[ResponseType(typeof(void))]
public IHttpActionResult Putstocks(StocksDTO stocks)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
stocks st = new stocks()
{
store_id = stocks.store_id,
product_id = stocks.product_id,
quantity = stocks.quantity
};
db.Entry(st).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!stocksExists(stocks.product_id, stocks.store_id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/stocks
[ResponseType(typeof(StocksDTO))]
public IHttpActionResult Poststocks(StocksDTO stocks)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
stocks st = new stocks()
{
store_id = stocks.store_id,
product_id = stocks.product_id,
quantity = stocks.quantity
};
db.stocks.Add(st);
try
{
db.SaveChanges();
}
catch (DbUpdateException)
{
if (stocksExists(stocks.store_id, stocks.product_id))
{
return Conflict();
}
else
{
throw;
}
}
return CreatedAtRoute("DefaultApi", new { id = stocks.store_id }, stocks);
}
// DELETE: api/stocks/5
[ResponseType(typeof(StocksDTO))]
public IHttpActionResult Deletestocks(int sId, int pId)
{
stocks stocks = db.stocks.Find(sId, pId);
if (stocks == null)
{
return NotFound();
}
StocksDTO stdto = new StocksDTO()
{
store_id = stocks.store_id,
product_id = stocks.product_id,
quantity = stocks.quantity,
product_name = stocks.products.product_name
};
db.stocks.Remove(stocks);
db.SaveChanges();
return Ok(stdto);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool stocksExists(int pId, int sId)
{
return db.stocks.Count(e => e.store_id == sId && e.product_id == pId) > 0;
}
}
}