I'm working in a ASP.NET MVC project and I have this particular situation: I have 3 pages - Product, Order, User. And in each of these pages I have a link calling the same ActionResult differing only by the argument passed depending on the page I'm in. For example:
public ActionResult(string typeOfPage)
{
if (typeOfPage == "User")
{
//do something
}
else if (typeOfPage == "Product")
{
//do other things
}
}
What I want to do now is to get all data from DB depending on "typeOfPage" value. And, of course, in dbml, all the entities have the same name as the typeOfPage value (User, Product开发者_如何学Go, Order).
I'm trying to avoid doing a specific IQueryable for each page, depending on typeOfPage value.
Is there a way to get this typeOfPage string value, get an Entity with the same name and use an IQueryable to get all data from this Entity??
Thanks a lot!!!
See my code below:
using System; using System.Data.Linq; using System.Linq;namespace MvcApplication1.Models { public class Repository : IRepository where TModel : class, new() { public DataContext dc; public string pk { get; set; } public Repository(DataContext dc) { this.dc = dc; }
#region IRepository<TKeyType,TModel> public IQueryable<TModel> getAllEntries() { return dc.GetTable<TModel>(); } #endregion }
}
using System; using System.Data.Linq; using System.Linq; namespace MvcApplication1.Models { public class Repository : IRepository where TModel : class, new() { public DataContext dc; public string pk { get; set; } public Repository(DataContext dc) { this.dc = dc; } #region IRepository public IQueryable getAllEntries() { return dc.GetTable(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; using MvcApplication1.Models; namespace MvcApplication1.Controllers { public class NorthwindController : Controller { // // GET: /Northwind/ NorthwindDataContext dc; Repository prdRepostory; Repository cstrRepostory; public NorthwindController() { this.dc = new NorthwindDataContext(); prdRepostory = new Repository(dc); cstrRepostory = new Repository(dc); } public ActionResult Index(string typeOfString) { if (typeOfString == "Products") { return RedirectToAction("getProducts"); } else if (typeOfString == "Customers") { return RedirectToAction("getCustomers"); } else return View(); } public ActionResult getProducts() { return View(prdRepostory.getAllEntries()); } public ActionResult getCustomers() { return View(cstrRepostory.getAllEntries()); } } }
For more information you should refer to the codeplex project MVCCRUD which is exactly what you want . Good luck !
精彩评论