在asp.net MVC中,有什么更好的替代方案可以直接访问Controller中的数据库

本文关键字:方案 数据库 Controller 访问 asp MVC 什么 更好 net | 更新日期: 2023-09-27 18:29:06

通常,我通过在控制器中全局安装DbContext来进行数据访问,然后使用它来操作我的数据。

见下文:

public class UserController : Controller
{
    private OrtundEntities db = new OrtundEntities();
    public ActionResult Create(CreateUserViewModel model)
    {
        try
        {
            UserDataModel user = new UserDataModel
            {
                // map view model fields to data model ones
            };
            db.Users.Add(user);
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            // some or other error handling goes here
        }
    }
}

我突然想到,这可能不是在所有应用程序中实现这一点的理想方式,但除了为我所做的每个项目实现web服务之外,我想不出任何替代方案。

那么,在以上情况不理想的大型项目中,有什么更好的方法来处理数据访问呢?

我只是在为这种或那种特殊情况寻找所谓的"最佳实践"。对于什么是最好的方式,很多人会有不同的看法,那么你认为是什么,为什么?

在asp.net MVC中,有什么更好的替代方案可以直接访问Controller中的数据库

为了帮助您的控制器保持简洁并且不直接访问数据库,您可以实现repositorydependency injection模式。对于更简洁的代码,您还可以使用unit of work模式。

假设你有这个型号:

public class Person {
   public int Id { get; set; }
   public string Name { get; set; }
}

在泛型的帮助下,您可以创建一个接口来提供CRUD蓝图:

public interface IRepository<T> {
    IEnumerable<T> Get();
    T Get(int? i);
    void Create(T t);
    void Update(T t);
    void Delete(int? i);
}

然后创建一个实现IRepository的Repository类。这就是你所有CRUD的发生地:

public class PersonRepository : IRepository<Person> {
    private OrtundEntities db = new OrtundEntities();
    public IEnumerable<Person> Get() {
        return db.Persons.ToList();
    }
    //invoke the rest of the interface's methods
    (...)
}

然后在您的控制器中,您可以调用dependency injection模式:

private IRepository<Person> repo;
public PersonController() : this(new PersonRepository()) { }
public PersonController(IRepository<Person> repo) {
    this.repo = repo;
}

比如说,Index()的控制器方法可能看起来像这样:

public ActionResult Index() {
    return View(repo.Get());
}

正如您所看到的,这有一些有用的好处,包括项目的结构,以及使控制器易于维护。

我认为您需要阅读http://chsakell.com/2015/02/15/asp-net-mvc-solution-architecture-best-practices/

更大的项目?大概https://msdn.microsoft.com/es-es/library/system.data.sqlclient.sqlcommand(v=vs.110).aspx

我在一些大的请求中使用这个。