如何在控制器中编写常用方法以在不同的表上执行CRUD操作?

时间:2015-07-28 10:42:56

标签: c# asp.net-mvc

我正在研究一个MVC项目。其中我有许多表格,例如LocationDepartmentSkillsStreamCurrentRole等。

我想对这些表执行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方法,它们可以接受我所有表的数据并执行操作。

正在编写通用方法解决方案吗?如果是,那我该如何实现呢?

有没有其他方法可以实现这个目标?

请帮助..

谢谢:)

1 个答案:

答案 0 :(得分:1)

由于您正在进行基本的CRUD操作,我建议您查看Repository pattern。 使用Repository模式的Generic接口示例:

<强> 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
}

请注意,在我的示例中,我使用的是Entity Framework

以下是使用Entity Framework实现Repository模式的有用指南:http://www.codeproject.com/Articles/688929/Repository-Pattern-and-Unit-of

相关问题