2012-05-31 25 views
0

我想用數據表中的行填充客戶模型,但一直無法獲得正確的語法。原代碼摘自本教程Your First ASP.NET Web API (C#)。我想用數據表中的行填充客戶模型

我已經添加了一個DataTable到控制器,但我一直無法弄清楚如何從表中獲取行到我的客戶模型中。我希望我可以用foreach來做,但正如我所說我無法獲得正確的語法。這是我的

Customer[] customers = new Customer[] 
    { 
     //new Customer {Id = "123", FirstName = "Buk", LastName = "Hix" } 
     // Replace hard coded customer information with foreach loop. 

     //commented out because it causes compile warnings 
     //foreach (DataRow row in GetAllData().Rows) 
     //{ 
     // yield return new Customer 
     // { 
     //  CustomerId = Convert.ToString(row["CustomerId"]), 
     //  FirstName = Convert.ToString(row["FirstName"]), 
     //  LastName = Convert.ToString(row["LastName"]) 
     // }; 
     //} 
    }; 

    public IEnumerable<Customer> GetAllCustomers() 
    {    
     return customers; 
    } 

什麼是最好的方式來完成我想要做的?

回答

1

你很近。在創建迭代器(返回使用yield的IEnumerable/IEnumerator的函數)時,您只需將代碼放入正文中即可。yield爲必要值。沒有必要把它們扔進另一個收藏。編譯器將爲代碼生成一個迭代器。

public IEnumerable<Customer> GetAllCustomers() 
{ 
    foreach (DataRow row in GetAllData().Rows) 
    { 
     yield return new Customer 
     { 
      CustomerId = row.Field<string>("CustomerId"), 
      FirstName = row.Field<string>("FirstName"), 
      LastName = row.Field<string>("LastName"), 
     }; 
    } 
} 

這將是更好的使用LINQ在這裏雖然如果你打開它。

public IEnumerable<Customer> GetAllCustomers() 
{ 
    return 
     from row in GetAllData().Rows 
     select new Customer 
     { 
      CustomerId = row.Field<string>("CustomerId"), 
      FirstName = row.Field<string>("FirstName"), 
      LastName = row.Field<string>("LastName"), 
     }; 
} 
+0

謝謝。當我跑步時,我沒有收到任何結果。在調試中,我在IEnumerable上設置了一個斷點,它甚至沒有觸及它。我是否需要做其他事情來確保被調用? –

+0

如果你沒有在循環中擊中任何斷點,那就意味着你找回的行是空的。你可以驗證你返回的'DataTable'(?)實際上是否包含數據? –

+0

是我的問題相關的JavaScript期待$ .getJSON(「api/customers /」,我現在正在返回客戶(選擇新客戶) –

2

你可以使用LINQ:

Customer[] customers = GetAllData() 
    .Rows 
    .Cast<DataRow>() 
    .Select(row => new Customer 
    { 
     CustomerId = Convert.ToString(row["CustomerId"]), 
     FirstName = Convert.ToString(row["FirstName"]), 
     LastName = Convert.ToString(row["LastName"]) 
    }) 
    .ToArray(); 

確保您已經添加System.Linqusing指令把範圍擴展方法。

相關問題