2015-10-21 181 views
1

我有一個方法旨在從OleDB中填充PersonModel;無法使用集合初始值設定項初始化類型'PeopleModel',因爲它沒有實現'System.Collections.IEnumerable'

public IEnumerable<PeopleModel> GetPeopleDetails() 
{ 
    var constr = ConfigurationManager.ConnectionStrings["dbfString"].ConnectionString; 
    using (var dbfCon = new OleDbConnection(constr)) 
    { 
     dbfCon.Open(); 
     using (var dbfCmd = dbfCon.CreateCommand()) 
     { 
      dbfCmd.CommandText = "SELECT pp_firstname, pp_surname, pp_title, pp_compnm, pp_hmaddr1, pp_hmaddr2, pp_hmtown, pp_hmcounty, pp_hmpcode, pp_spouse, pp_children FROM people ORDERBY pp_surname"; 
      using (var myReader = dbfCmd.ExecuteReader()) 
      { 
       var peopleList = new List<PeopleModel>(); 
       while (myReader.Read()) 
       { 
        var details = new PeopleModel 
        { 
         details.Firstname = myReader[0].ToString(), 
         details.Lastname = myReader[1].ToString(), 
         details.Title = myReader[2].ToString(), 
         details.Company = myReader[3].ToString(), 
         details.Addr1 = myReader[4].ToString(), 
         details.Addr2 = myReader[5].ToString(), 
         details.Town = myReader[6].ToString(), 
         details.County = myReader[7].ToString(), 
         details.Spouse = myReader[8].ToString(), 
         details.Children = myReader[9].ToString(),        
        }; 
        peopleList.Add(details); 
       } 
       return peopleList; 
      } 
     } 
    } 
} 

此代碼與我用於填寫公司詳細信息的方法非常相似,這不會造成任何問題。這是我用來建立一個人的PeopleModel。

namespace SdcDatabase.Model 
{ 
    public class PeopleModel 
    { 
     public string Firstname { get; set; } 
     public string Lastname { get; set; } 
     public string Title { get; set; } 
     public string Company { get; set; } 
     public string Addr1 { get; set; } 
     public string Addr2 { get; set; } 
     public string Town { get; set; } 
     public string County { get; set; } 
     public string Spouse { get; set; } 
     public string Children { get; set; } 
    } 
} 

雖然公司的方法以前工作得很好,我現在得到以下錯誤,當我試圖實現人民代碼後建立我的項目:因爲它無法與集合初始化初始化類型「PeopleModel」不實施'System.Collections.IEnumerable'

我真的在一個失敗的原因與此,因爲它是在一個公司幾乎相同的方法工作。

+0

[如何:初始化通過使用對象初始化對象(https://msdn.microsoft.com/en-us/library /bb397680.aspx) – Ric

回答

3

正確的語法,而不在初始化所述分配details.

var details = new PeopleModel 
{ 
    Firstname = myReader[0].ToString(), 
    Lastname = myReader[1].ToString(), 
    Title = myReader[2].ToString(), 
    Company = myReader[3].ToString(), 
    Addr1 = myReader[4].ToString(), 
    Addr2 = myReader[5].ToString(), 
    Town = myReader[6].ToString(), 
    County = myReader[7].ToString(), 
    Spouse = myReader[8].ToString(), 
    Children = myReader[9].ToString(),        
}; 
相關問題