【问题标题】:Questions about business logic layer and data access layer in a project关于项目中业务逻辑层和数据访问层的问题
【发布时间】: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
  • 这类问题的论坛不适合,但看起来还不错。
  • 我将论证您的前提,即基于 EF 的存储库是最佳实践。很多争论,对我来说,这取决于你是否打算换掉数据库。请参阅 herehere。服务层是的,存储库 - 不一定。
  • 对不起,如果我在错误的地方插入帖子,我应该在哪里发布?还是谢谢
  • 关于检查存在性的问题,我们使用remote client validation

标签: c# .net visual-studio entity-framework


【解决方案1】:

最好使用.Any() 以获得更清晰的含义。

var dbProductExists = dbContext.PRODUCTS.Any(p => p.NAME == name);

if(dbProductExists) .... // insert else throw exception 

如果您想返回现有记录以进行编辑,请使用.FirstOrDefault()

我认为性能没有差异 - 当他们发现第一次出现时,两者都会停止。

【讨论】:

    猜你喜欢
    • 2013-03-23
    • 2010-10-02
    • 2012-08-30
    • 2012-07-06
    • 1970-01-01
    • 2012-11-26
    • 2011-05-30
    • 2011-07-27
    • 2016-06-28
    相关资源
    最近更新 更多