如何在控制器中编写通用方法来对不同的表执行CRUD操作?

本文关键字:执行 操作 CRUD 方法 控制器 | 更新日期: 2023-09-27 18:05:18

我正在做一个MVC项目。其中我有许多表,如Location, Department, Skills, Stream, CurrentRole等。

我想在这些表上执行CRUD操作。

我所做的是我写了一些方法来执行Location表的操作。有如下4种方法

添加位置:

public ActionResult AddLocation(tblCurrentLocation location)
        {
            //Logic to add location to the database.
        }

编辑位置:

   public ActionResult EditLocation(string id)
        {
            //Logic to display Edit form...
        }

保存编辑后的数据:

  [HttpPost]
        public ActionResult SaveLocation(tblCurrentLocation tblCurrentLocation)
        {
            //Logic to update the data in database.
//This is POST method which will get called when user clicks 
//save after editing the data.
        }

,这是为了从数据库

中删除条目
 public ActionResult DeleteLocation(int id)
        {
            //Logic to delete row from database.
        }

如果我遵循这种方法并写下所有(大约)的方法。16)表,它将像50+方法在我的控制器很难维护。

我正在寻找的是我将编写通用的CRUD方法,它将能够接受所有表的数据并执行操作。

泛型方法是一个解决方案吗?如果是,那么我该如何实现呢?

是否有其他方法来实现这一点?

请帮. .

谢谢你

如何在控制器中编写通用方法来对不同的表执行CRUD操作?

既然您正在执行基本的CRUD操作,我建议您查看Repository模式。使用Repository模式的通用接口示例:

IRepository

public interface IRepository<T> where T : IEntity
{
    IEnumerable<T> List { get; }
    void Add(T entity);
    void Delete(T entity);
    void Update(T entity);
    T FindById(int id);
}

IEntity

public class IEntity
{
    public int Id {get;set;}
}

示例实现

public class MyRepo : IRepository<MyClass> // MyClass needs to implement IEntity
{
    private readonly DBContext _context;
    public MyRepo(DBContext context)
    {
        _context = context;
    }
    public List<MyClass> List()
    {
        return _context.Table.ToList();
    }
    // Other implementations of the IRepository interface
}

请注意,在我的例子中,我使用实体框架

下面是使用实体框架实现存储库模式的有用指南:http://www.codeproject.com/Articles/688929/Repository-Pattern-and-Unit-of