c# - 为什么这个 linq 表达式不起作用?

标签 c# asp.net linq linq-to-entities

我正在使用 LINQ to Entities。

我有一个名为 Student 的表;它有 ID 和 Name 作为它的列。 ID 是主键。

我希望能够选择学生的姓名并获得具有相同姓名的学生的数量。

例如,我会将其作为我的表数据。

ID  Name  
1   Bob
2   Will
3   Bob

执行查询后,我将返回一个 Student 对象列表,如下所示。

Name    Quantity
Bob     2
Will    1

我想这有点类似于 stackoverflow 的标签页面的工作方式;它有名称和数量。

无论如何,我创建了一个名为 Student.cs 的部分类,我在其中添加了一个像这样的 Quantity 属性。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MySite.Models
{
    public partial class Student
    {
        private int _quantity;

        public int Quantity
        {
            get { return _quantity; }
            set { _quantity = value; }
        }
    }
}

我想到了这个,但我遇到了一个错误..

    public IQueryable<Student> FindStudentsDistinctWithQuantity()
    {
        /*SELECT Name, COUNT(Name) AS Quantity
        FROM Student
        GROUP BY Name*/

        var students= (from s in db.Students
                    group s by s.Name into g
                    select new {Name = g.Key, Quantity = g.Count()});            

        return students;
    }

我得到的错误是类似无法从匿名类型转换为学生列表。是不是和我在partial class里面加的quantity字段没有识别有关系?

谢谢!

最佳答案

更改您的 Student键入如下所示:

public partial class Student
{
    public Int32 Quantity { get; set; }
    public String Name { get; set; }
}

你的查询看起来像这样:

var students = from s in db.Students
               group s by s.Name into g
               select new Student { 
                   Name = g.Key, 
                   Quantity = g.Count() };

您的方法返回 IQueryable<Student>但您目前返回的是 IQueryable<T>一个预计的匿名类型。

您需要重构您的 Student输入 Name类型属性 String然后转换你的 Student 的新实例从表达式中输入类型,以便表达式的返回类型与方法的返回类型相匹配。

关于c# - 为什么这个 linq 表达式不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2157493/

相关文章:

c# - 同一实体的多个 Dto

c# - 单击按钮时 gridview 内的文本框值为空

c# - 在不重新加载页面的情况下提交 TextBox 的值

c# - 使用字典键过滤列表

c# - 如何在 .NET 中使 Google 可抓取 AJAX 分页

c# - 如何在Visual Studio中找到哪个 `method`来自哪个 `namespace`

asp.net - MVC 未检测到我的自定义 httpModule

c# - 使用 Linq 表达式在通用存储库中实现搜索

c# - 为 LINQ to Objects 定义我自己的 Where-Method - 我如何知道将使用哪一个?

c# - 强类型数据集作为用户定义的表类型参数