2012-03-26 77 views
0

我想從一個名爲「Customer」的表中選擇一些行,但是當我使用「db.Customer」定義tableName時,它似乎是錯誤的。有什麼辦法可以做到嗎?如何在LINQ to ENTITIES select語句中使用變量?

  string tableName = "db.Customer"; 
      var result = from p in tableName 
        select new 
        { 
         ID = p.ID, 
         Des = p.Description, 
         type = p.Type, 
         date = p.DateCreated 

        }; 
     gridview.DataSource = result; 
     gridview.DataBind(); 

回答

0

可以使用CreateQuery方法(接收實體SQL命令)

var result = ctx.CreateQuery<DbDataRecord>(@"select p.ID, 
                 p.Description, 
                 p.Type, 
                 p.DateCreated 
               from Customer as p"); 

ExecuteStoreQuery或(執行T-SQL)

var result = ctx.ExecuteStoreQuery<CustomerInfo>(@"select p.ID, 
                  p.Description, 
                  p.Type, 
                  p.DateCreated 
                from dbo.Customer as p"); 


public class CustomerInfo 
{ 
    public int ID {get; set;} 
    public string Description {get; set;} 
    public int Type {get; set;} 
    public DateTime DateCreated {get; set;} 
}