我正在使用LINQ to Entities。爲什麼這個linq表達式不起作用?
我有一張名爲Student的表;它具有ID和名稱,因爲它是列。 ID是主鍵。
我希望能夠選擇學生的姓名並獲得具有相同姓名的學生人數。
因此,例如,我會把這個作爲我的表格數據。
ID Name
1 Bob
2 Will
3 Bob
執行查詢後,我會返回一個Student對象列表,看起來像這樣。
Name Quantity
Bob 2
Will 1
我想這有點類似於stackoverflow標籤頁的工作原理;它有名字和數量。
無論如何,我創建了一個名爲Student.cs的部分類,其中我添加了一個像這樣的數量屬性。
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;
}
,我發現了錯誤說像無法從類型轉換匿名向學生名單。它與它沒有關係,不能識別我在分部類中添加的數量字段?
謝謝!
一些一般性的建議是:直到你獲得更多的經驗停止使用VAR 。如果你曾嘗試使用'IQueryable =(來自...',那麼你就會在問題上得到更快的處理速度。 –
2010-01-28 20:56:49