I'm in the process of delving into different design patterns and trying to implement them into my daily work routine.
I come from an unstructured world of PHP and not understanding how to utilize it to its potential. I have recently switched over to C# and I'm trying to unlearn some bad habits I picked up through my lack of understanding.
I have some of my WebAPI project, which will grow in the future so I'm trying to plan for that now. Please review the code and see if I have implemented a repository pattern correctly. The code is 100% functional but I put it together out of a few eBooks I'm reading and a few articles I found online.
Simple interface with only one method:
public interface IProductRepository
{
ProductViewModel GetProduct(string ProdNum);
}
}
Product Repository Class:
public class ProductRepository : IProductRepository
{
private ProductMaterialEntities pd;
public ProductRepository(ProductMaterialEntities product)
{
pd = product;
}
public ProductViewModel GetProduct(string prodNum)
{
var result1 = pd.products.Where(x => x.ProdNum == prodNum).FirstOrDefault();
var result2 = pd.ProductImagePaths.Where(x => x.ImageProdNum == prodNum).FirstOrDefault() ?? new ProductImagePath();
if (result1 != null)
{
ProductViewModel product = new ProductViewModel()
{
ProdID = result1.ProdID,
ProdNum = result1.ProdNum,
ProdCode = result1.ProdCode,
.
.
.
.//whole bunch of attributes
ImageCompany = result2.ImageCompany
};
return product;
}
//return empty ProductViewModel if nothing is found
return new ProductViewModel();
}
}
Default controller
public class ValuesController : ApiController
{
private IProductRepository productRepository;
public ValuesController()
{
productRepository = new ProductRepository(new ProductMaterialEntities());
}
[Route("Product/GetProduct/{prodNum}")]
// Access via: http://xxxxxxxxx/Product/GetProduct/02130
public IHttpActionResult GetProduct(string prodNum)
{
var productInfo = productRepository.GetProduct(prodNum);
if (productInfo.ProdID <= 0)
{
return NotFound();
}
return Ok(productInfo);
}
}