2015-07-28 59 views
1

我正在开发一个MVC项目。在这我有很多表像LocationDepartmentSkillsStreamCurrentRole如何在控制器中编写通用方法来在不同的表上执行CRUD操作?

我想对这些表执行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

@AndreiV你能举一些例子吗? 或链接... 谢谢 –

回答

1

既然你是预成型基本的CRUD操作,我建议看Repository pattern。 使用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

+0

嘿@jamie里斯谢谢您的回答... 我查一下,如果这个工程第一件事就是在早上 –

+0

感谢您的回答和链接... 它工作正常 –

+0

那是个好消息。乐意效劳。 –