将 Entity Framework 6 个项目分成几层

Separating Entity Framework 6 projects into layers

我正在阅读有关 Entity Framework 6 的教程,并尝试将其实施到测试项目中。这将针对 ASP .Net webforms,但我认为原则对于 MVC 项目是相同的。

我有 3 个项目 DAL、BAL 和 Webforms 项目。

我创建了一个名为 DAL 的 Class 库,安装 EF 6。将 ADO.Net 实体数据模型 link 添加到数据库。这有 2 tables 以方便客户和地址。连接字符串存储在 app.config 文件中。

Table 1 (Customers)- Id, Firstname, Surname
Table 2 (Addresses)- Id, PrimaryAddress, CustomerId
  1. 我看到一个 .tt 文件并展开它我看到所有 class 与我的数据库 table 相似。如果我想添加另一种方法,即

    Public string GetCustomerFullName
    {
      return Firstname + " " + Surname;
    }
    

在 DAL 项目中,我将在何处以及如何执行此操作?我正在考虑在扩展 .tt 文件(即客户 class)时创建的 Class,但我有一种偷偷摸摸的感觉,如果我要重新生成/刷新 [=39] 的某些部分,这可能会被覆盖=] 实体数据模型文件,例如如果添加 table 什么的?

  1. 我创建了另一个名为 BAL 的 Class 库(这是我想调用所有 CRUD 操作的地方)。从 Nuget 安装 EF6。我添加了对 DAL 项目的引用。目前,本教程为同一项目中的每个方法(即添加、更新等)添加了一个新的 Dbcontext 实例。

如何在本项目中引用DAL项目中创建的DbContext?我读过很多线程,新的上下文可能会产生奇怪的行为,而其他人觉得重用相同的上下文 is/not 是个好主意。有人能告诉我如何以正确的方式引用 DbContext 吗?我通常有一个摘要 class 然后添加到我的 classes 例如

    public class CustomerService : DbContxtService, ICustomer
    {
     public void Add(Customer c)
    {
    // Add customer
    }
    }
  1. 如何设置 DAL 项目以从我的 Web 表单项目中检索连接字符串(这样我就不需要总是更改 Class 库并且可以有一个区域来更改连接字符串)

If i want to add another method.. where would I do it.

实体定义为partial classes。您可以在不会被覆盖的单独文件中向 class 添加成员。

How do i reference the DbContext created in DAL project in this project?

您设置了对项目的引用,并为您的(单个)DbContext 上的每个服务添加了构造函数依赖项。

例如

public class CustomerService 
{
    private MyDbContext db;
    public CustomerService(MyDbContext db)
    {
       this.db = db;
    {
    public void CreateNewCustomer(Customer c)
    {
       //CRUD and business logic here
       ...
       db.SaveChanges();
    }
    public Customer GetCustomerWithHistory(int customerId)
    {
       db.Customer.Include("SalesOrders").FirstOrDefault( c => c.Id = customerId);
    }

    public void CreateCustomerServiceTicket(Customer c, Incident i)
    {
    }
}

请注意,这应该是业务服务,而不是存储库。