我正在使用 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/