【问题标题】:Using LINQ in an MVC project, how can I orderby a joined table's value?在 MVC 项目中使用 LINQ,如何按连接表的值排序?
【发布时间】:2019-05-02 21:29:31
【问题描述】:

我有两个班级要一起参加:

物品

(一堆属性)

(外键)int类别

类别

(主键)int ID(在Item中引用)

字符串名称

在我的 MVC 5 项目中使用 LINQ,我需要使用 Item 表中的 ID 从类别表中获取 Name 值并按其排序。使用下面的代码,它按整数 (1,2,3,4) 的顺序排序,而不是按 Category 表中的 Name 属性。如何按类别表排序?

控制器代码:

var items = from s in db.Items 
            join c in db.Categories on s.Category equals c.ID
            select s;

switch (sortOrder)
        {
            case "Category_Desc":
                //This is where it is selecting the integer ID instead of the string Name
                items = items.OrderByDescending(s => s.Category);
                break;
            default:
                items = items.OrderBy(s => s.Category);
                break;
        }

【问题讨论】:

    标签: asp.net-mvc linq


    【解决方案1】:

    Item 类的 Category 属性是一个 int,因此它将像对任何其他整数一样对它们进行排序。现在,您的联接没有任何作用,因为您只选择查询结束时的项目。选择一个同时包含类别和项目的匿名对象,然后您将可以访问 Category 类的属性,并且可以按名称排序并仅选择 Item

    var query= from s in db.Items 
            join c in db.Categories on s.Category equals c.ID
            select new { item = s, cat = c };
    switch (sortOrder)
    {
        case "Category_Desc":
            //This is where it is selecting the integer ID instead of the string Name
            items = items.OrderByDescending(s => s.cat.Name);
            break;
        default:
            items = items.OrderBy(s => s.cat.Name);
            break;
    }
    var items = query.Select(s => s.item);
    

    【讨论】:

    • 这正是我所需要的!我也喜欢 Anu 的回答,但您的回答与我已经使用的语法相似。另请注意:我必须在 query.select 中将 select 上的 S 大写并将其更改为 query.Select。
    • @sjohn285 我已经编辑了答案并将 S 大写。很高兴我能提供帮助。
    【解决方案2】:

    你可以试试关注

    您可以尝试关注。

    var result = db.Items
                .Join(db.Categories,i=> i.Category, c=>c.Id,(i,c)=>new {item =i, category=c})
                .OrderBy(x=>x.category.Name).Select(x=>x.item);
    

    关键是创建一个临时结构,其中包含 Category.Name。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-14
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 2016-02-25
      • 2015-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多