【问题标题】:How can I make a generic IQueryable in Linq?如何在 Linq 中制作通用 IQueryable?
【发布时间】:2010-12-10 20:34:00
【问题描述】:

我在一个 ASP.NET MVC 项目中工作,我遇到了这种特殊情况:我有 3 个页面 - 产品、订单、用户。在每个页面中,我都有一个链接调用相同的 ActionResult,不同之处仅在于传递的参数取决于我所在的页面。例如:

public ActionResult(string typeOfPage)
{
   if (typeOfPage == "User")
   {
      //do something
   }
   else if (typeOfPage == "Product")
   {
      //do other things
   }
}

我现在要做的是根据“typeOfPage”值从数据库中获取所有数据。当然,在 dbml 中,所有实体都具有与 typeOfPage 值(用户、产品、订单)相同的名称。

我试图避免为每个页面执行特定的 IQueryable,具体取决于 typeOfPage 值。

有没有办法获取这个typeOfPage字符串值,获取一个同名的Entity并使用一个IQueryable从这个Entity中获取所有数据??

非常感谢!!!

【问题讨论】:

    标签: asp.net-mvc linq-to-sql generics c#-3.0 iqueryable


    【解决方案1】:

    请参阅下面的代码:

    使用系统; 使用 System.Data.Linq; 使用 System.Linq;

    命名空间 MvcApplication1.Models { 公共类存储库:IRepository 其中 TModel :类,新() { 公共数据上下文直流; 公共字符串 pk { 获取;放; } 公共存储库(DataContext dc) { this.dc = 直流; }

        #region IRepository<TKeyType,TModel> 
    
        public IQueryable<TModel> getAllEntries()
        {
            return dc.GetTable<TModel>();
        }
    
        #endregion
    }
    

    }

    使用系统; 使用 System.Data.Linq; 使用 System.Linq; 命名空间 MvcApplication1.Models { 公共类存储库:IRepository 其中 TModel :类,新() { 公共数据上下文直流; 公共字符串 pk { 获取;放; } 公共存储库(DataContext dc) { this.dc = 直流; } #region IRepository 公共 IQueryable getAllEntries() { 返回 dc.GetTable(); } #endregion } } 使用系统; 使用 System.Collections.Generic; 使用 System.Linq; 使用 System.Web; 使用 System.Web.Mvc; 使用 System.Web.Mvc.Ajax; 使用 MvcApplication1.Models; 命名空间 MvcApplication1.Controllers { 公共类 NorthwindController : 控制器 { // // 获取:/罗斯文/ 北风数据上下文直流; 存储库prdRepostory; 存储库 cstrRepostory; 公共北风控制器() { this.dc = new NorthwindDataContext(); prdRepostory = 新存储库(dc); cstrRepostory = new Repository(dc); } 公共 ActionResult 索引(字符串 typeOfString) { if (typeOfString == "产品") { return RedirectToAction("getProducts"); } else if (typeOfString == "Customers") { return RedirectToAction("getCustomers"); } 否则返回视图(); } 公共 ActionResult getProducts() { 返回视图(prdRepostory.getAllEntries()); } 公共 ActionResult getCustomers() { 返回视图(cstrRepostory.getAllEntries()); } } }

    有关更多信息,您应该参考 codeplex 项目MVCCRUD,这正是您想要的。祝你好运!

    【讨论】:

      猜你喜欢
      • 2013-01-05
      • 2019-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      相关资源
      最近更新 更多