2014-09-04 52 views
-2

我有表名爲Pinfo我想要做的是從數據庫中使用Linq查詢獲取記錄並返回它。但我無法做到這一點。這是我到目前爲止。我如何使這項工作我怎樣才能使數據表爲可枚舉

List<ProductInfo> getList() 
{ 
    List<ProductInfo> pi = new List<ProductInfo>(); 
    using (SqlConnection con = new SqlConnection("server=.\\sqlexpress;database=Project;User Id=sa;Password=1")) 
    { 
     con.Open(); 
     using (SqlCommand cmd = new SqlCommand("select * from PInfo", con)) 
     { 

      SqlDataAdapter adp = new SqlDataAdapter(cmd); 
      DataTable dt = new DataTable(); 
      var query = from c in dt.AsEnumerable() 
         select new 
         { 
          id = c.Field<int>("Id"), 
          name = c.Field<string>("Name"), 
          price = c.Field<decimal>("Price") 

         }; 
      adp.Fill(query); 
     } 
    } 

    return pi; 
} 
+0

我想你忘了在迭代結果之前運行實際查詢 – Greenonion 2014-09-04 13:55:55

+0

該表爲空。您不能像使用Linq-To-SQL一樣使用ADO.NET。你必須先使用'adp.Fill(dt)'。然後你可以使用'Linq-To-DataTable'('Linq-To-Objects')來查詢表格。 – 2014-09-04 14:02:31

回答

0

嘗試這種方式

DataTable dt = new DataTable(); 
dt.Load(cmd.ExecuteReader()); 

return (from c in dt.AsEnumerable() 
     select new ProductInfo 
       { 
        id=c.Field<int>("Id"), 
        name=c.Field<string>("Name"), 
        price=c.Field<decimal>("Price") 

       }).ToList(); 
  • ,如果你想返回的ProductInfos
  • 列表您不需要你不應該創建匿名類型SqlDataAdapter,只需使用Load方法的DataTable。