【发布时间】:2018-01-26 14:18:17
【问题描述】:
作为最佳实践,我会将 BLL 与 DAL 分开。我通过接口在 BLL 和 DAL 之间进行交互。 示例:
public interface IProductRepository
{
void Add(Product myProduct);
Product Get(string name);
Product GetById(int id);
}
业务对象产品在哪里:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
BLL 类是:
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
}
DAL(我会使用实体框架)在哪里:
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
}
现在我有一些问题: - 这是正确的实现吗? - 如果我想插入一个产品,但我想检查一个同名的产品是否在 db 上,我是先调用 Get 方法还是可以在 DAL 中插入逻辑,例如:
var dbProduct = dbContext.PRODUCTS.FirstOrDefault(p => p.NAME == name);
if(dbProduct == null) .... // insert else throw exception
-这样使用EntityFramework是否正确,还是我失去了linq的所有好处? 对不起,我很困惑。
谢谢。
【问题讨论】:
-
这可能更适合 CodeReview.SE
-
这类问题的论坛不适合,但看起来还不错。
-
对不起,如果我在错误的地方插入帖子,我应该在哪里发布?还是谢谢
-
关于检查存在性的问题,我们使用remote client validation。
标签: c# .net visual-studio entity-framework