加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-3 – 如何在ASP.NET MVC 3中分离代码(清除代码分离)

发布时间:2020-12-16 06:22:56 所属栏目:asp.Net 来源:网络整理
导读:我现在只想知道如何使用EF在MVC3中以正确的方式分离代码 根据我的项目结构. 演示 – 查看调节器 域名 – 模型(商业实体) 数据 – RepositoryBase,IRepository,ApplicationDbContext 服务 – 第三方服务(PayPal,SMS)或应用服务 ApplicationDbContext需要Model
我现在只想知道如何使用EF在MVC3中以正确的方式分离代码

根据我的项目结构.

演示 – >查看&调节器

域名 – >模型(商业实体)

数据 – > RepositoryBase,IRepository,ApplicationDbContext

服务 – >第三方服务(PayPal,SMS)或应用服务

ApplicationDbContext需要Model作为参考.

public sealed class ApplicationDbContext : DbContext
{

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

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

1.将DbContext放入数据是否合适?或者我必须将其移至域名?

现在在Controller中我必须编写代码

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?

请建议我正确的方法.

解决方法

So is it good to place DbContext in Data ?

是的,这是它所属的地方.

Now in Controller I have to write a code

不,你绝对不应该在控制器中编写这样的代码,因为你现在正在使你的控制器与你正在使用的特定数据访问技术紧密耦合(在你的情况下是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.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读