I would separate the BLL from DAL as a best practice. I interact between BLL and DAL via interface. Example:
public interface IProductRepository { void Add(Product myProduct); Product Get(string name); Product GetById(int id); }
where business object Product is:
public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } }
The BLL class is:
public class ProductManager { private readonly IProductRepository productRepository; public ProductManager(IProductRepository productRepository) { this.productRepository = productRepository ?? throw new Exception("message"); } public void AddProduct(Product myProduct) { try { // Here code validation ecc.... // Add product to database productRepository.Add(myProduct); } catch(Exception e) { // Handle exception } } public Product GetProduct(string name) { try { // Here code to validation ecc.... // Get product from database var product = _productRepository.Get(name); return product; } catch(Exception e) { // Handle exception } } // ecc ecc }
where DAL (i would use Entity Framework) is:
public ProductRepository : IProductRepository { public void Add(Product myProduct) { using(var dbContext = MyDbContext()) { var dbProduct = new PRODUCTS { NAME = myProduct.Name, PRICE = myProduct.Price } dbContext.PRODUCT.Add(dbProduct); dbContext.SaveChanges(); } } // ecc ecc }
Now I have some questions: – Is this the correct implementation? – If I want insert a product but I want to check if a product with the same name is on db, do I first call the Get method in BLL and then call Add method (the db context is open and closed each time, is an overload?) or I can insert logic in DAL like:
var dbProduct = dbContext.PRODUCTS.FirstOrDefault(p => p.NAME == name); if(dbProduct == null) .... // insert else throw exception
In the latter case, however, if a change the dal the bll logig would no work anymore. -Is it right to use EntityFramework in this way, or do I lose all the benefits of linq? Sorry, but i’m very confused.
Thank you.