han*_*sjw 5 c# linq asp.net linq-to-entities
我正在使用LINQ to Entities.
我有一张叫做学生的桌子; 它有ID和Name作为列.ID是主键.
我希望能够选择学生的姓名并获得具有相同姓名的学生数量.
例如,我将此作为我的表格数据.
ID Name
1 Bob
2 Will
3 Bob
Run Code Online (Sandbox Code Playgroud)
执行查询后,我将返回一个如下所示的Student对象列表.
Name Quantity
Bob 2
Will 1
Run Code Online (Sandbox Code Playgroud)
我想这有点类似于stackoverflow的Tags页面的工作原理; 它有名称和数量.
无论如何,我创建了一个名为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; }
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想出了这个,但我收到了一个错误..
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;
}
Run Code Online (Sandbox Code Playgroud)
我得到的错误说不能从匿名类型转换为学生列表.它是否与它有关而没有识别我在分部类中添加的数量字段?
谢谢!
将您的类型更改Student为如下所示:
public partial class Student
{
public Int32 Quantity { get; set; }
public String Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
您的查询如下所示:
var students = from s in db.Students
group s by s.Name into g
select new Student {
Name = g.Key,
Quantity = g.Count() };
Run Code Online (Sandbox Code Playgroud)
您的方法返回 an IQueryable<Student>,但您当前返回的是IQueryable<T>投影匿名类型的 an 。
您需要重构Student类型以具有Nametype 属性String,然后Student从表达式中投影类型的新实例,以便表达式的返回类型与方法的返回类型匹配。
| 归档时间: |
|
| 查看次数: |
2123 次 |
| 最近记录: |