4

我现在只想知道如何使用 EF 在 MVC3 中以正确的方式分离代码

根据我的项目结构。

演示 -> 视图和控制器

域 --> 模型(业务实体)

数据 --> RepositoryBase、IRepository、ApplicationDbContext

服务 --> 第三方服务(PayPal、SMS)或应用服务

ApplicationDbContext 需要模型作为参考。

public sealed class ApplicationDbContext : DbContext
{

    public DbSet<CountryModel> Country { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

1. 那么将 DbContext 放在 Data 中好吗?还是我必须将其移至 Domain ?

现在在控制器中我必须编写代码

using (ApplicationDbContext db = new ApplicationDbContext())
{
    var countryRepository = new Repository<Country>(db);

    if (ModelState.IsValid)
    {
        countryRepository.insert(country);
        db.SaveChanges();
    }
}

有什么方法可以将此代码块分离为任何业务层/服务层?

所以我们只需从控制器调用该层并传递特定的业务实体以执行其余操作。

我想做 PL --> BLL --> DLL 方法使用 MVC 3 & EF 吗?

请建议我正确的方法。

4

2 回答 2

2

那么将 DbContext 放在 Data 中好吗?

是的,它属于它。

现在在控制器中我必须编写代码

不,您绝对不应该在控制器中编写这样的代码,因为您现在正在使您的控制器与您正在使用的特定数据访问技术(在您的情况下为 EF)强耦合。更糟糕的是,您将无法单独对控制器进行单元测试。

我建议您对接口中的实体进行抽象操作(顺便说一下,您已经在问题中提到了它 - IRepository)。现在您的控制器可以将存储库作为依赖项:

public class CountriesController: Controller
{
    private readonly IRepository repository;
    public CountriesController(IRepository repository)
    {
        this.repository = repository;
    }

    public ActionResult Index(int id)
    {
        Country country = this.repository.Get<Country>(id);
        return View(country);
    }


    [HttpPost]
    public ActionResult Index(Country country)
    {
        if (ModelState.IsValid)
        {
            this.repository.Insert(country); 
            return RedirectToAction("Success");
        }

        return View(country);
    }
}

现在你所要做的就是配置你最喜欢的依赖注入框架,将这个 IRepository 的具体实现注入到控制器构造函数中。在您的情况下,此特定实现可能是某个实现 IRepository 接口并使用ApplicationDbContext内部的类。

这样,您就可以从控制器中抽象出数据访问逻辑。

于 2013-01-08T07:32:57.073 回答
2

您可以在 BLL 中为彼此创建单独的项目,为每个业务实体调用存储库表单创建类,并创建一些您需要的基本功能,例如插入删除查找带参数的选择等

var country =new Country();//it's class of BLL

if (ModelState.IsValid)
{
    country.insert(country);
}

类似的东西

于 2013-01-08T07:28:07.583 回答