HOW TO:執行傳回匿名型別集合的查詢 (Entity Framework)
本主題提供的範例將說明如何執行會傳回匿名型別之執行個體集合的查詢。 匿名型別就是在概念模型中未定義的型別。 例如,下列 Entity SQL 查詢會傳回匿名型別的集合,其中包含具有兩個資料行 (ProductID 的整數和 Name 的字串) 的資料列:"SELECT p.ProductID, p.Name FROM AdventureWorksEntities.Products as p"
。 下列範例會傳回 Products 的集合,以及概念模型中所定義之 Product 型別:"SELECT p FROM AdventureWorksEntities.Products as p"
。
相同範例會使用下列每個 Entity Framework 查詢技術來顯示:
LINQ to Entities
Entity SQL with ObjectQuery<T>
Query builder methods of ObjectQuery<T>
本主題的範例根據 Adventure Works Sales Model。若要執行此主題中的程式碼,您必須已經將 Adventure Works Sales Model 加入到專案中,並設定您的專案使用 Entity Framework。如需詳細資訊,請參閱 HOW TO:使用實體資料模型精靈 (Entity Framework) 或 HOW TO:手動設定 Entity Framework 專案及 HOW TO:手動設定 Entity Framework 專案。
範例
以下是 LINQ to Entities 範例。
Using context As New AdventureWorksEntities
Dim products As ObjectSet(Of Product) = context.Products
Dim query = _
From product In products _
Select New With _
{ _
.ProductId = product.ProductID, _
.ProductName = product.Name _
}
Console.WriteLine("Product Info:")
For Each productInfo In query
Console.WriteLine("Product Id: {0} Product name: {1} ", _
productInfo.ProductId, productInfo.ProductName)
Next
End Using
using (AdventureWorksEntities context = new AdventureWorksEntities())
{
var query =
from product in context.Products
select new
{
ProductId = product.ProductID,
ProductName = product.Name
};
Console.WriteLine("Product Info:");
foreach (var productInfo in query)
{
Console.WriteLine("Product Id: {0} Product name: {1} ",
productInfo.ProductId, productInfo.ProductName);
}
}
以下是 Entity SQL 範例。
Using context As New AdventureWorksEntities()
Dim myQuery As String = "SELECT p.ProductID, p.Name FROM AdventureWorksEntities.Products as p"
For Each rec As DbDataRecord In New ObjectQuery(Of DbDataRecord)(myQuery, context)
Console.WriteLine("ID {0}; Name {1}", rec(0), rec(1))
Next
End Using
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
string myQuery = @"SELECT p.ProductID, p.Name FROM
AdventureWorksEntities.Products as p";
foreach (DbDataRecord rec in
new ObjectQuery<DbDataRecord>(myQuery, context))
{
Console.WriteLine("ID {0}; Name {1}", rec[0], rec[1]);
}
}
以下是查詢產生器方法範例。
Using context As New AdventureWorksEntities()
' Use the Select method to define the projection.
Dim query As ObjectQuery(Of DbDataRecord) = context.Products.Select("it.ProductID, it.Name")
' Iterate through the collection of data rows.
For Each rec As DbDataRecord In query
Console.WriteLine("ID {0}; Name {1}", rec(0), rec(1))
Next
End Using
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
// Use the Select method to define the projection.
ObjectQuery<DbDataRecord> query =
context.Products.Select("it.ProductID, it.Name");
// Iterate through the collection of data rows.
foreach (DbDataRecord rec in query)
{
Console.WriteLine("ID {0}; Name {1}", rec[0], rec[1]);
}
}
另請參閱
工作
HOW TO:執行傳回實體類型物件的查詢 (Entity Framework)
HOW TO:執行傳回基本型別集合的查詢
HOW TO:執行參數化查詢 (Entity Framework)