1

我在一个 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 字符串值,获取一个同名的实体并使用 IQueryable 从这个实体获取所有数据?

非常感谢!!!

4

1 回答 1

2

请参阅下面的代码:

使用系统;
使用 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,这正是您想要的。祝你好运 !

于 2009-10-28T16:05:32.020 回答