1

如何從下面的程序返回List<personel>數據類型。如果我按F5扔我這個錯誤:如何使用Entity Framework在Linq中編寫列表類型返回值?

Error 1 Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?) C:\Documents and Settings\yusufk\Desktop\EFTestSolutions\WebApplicationTest1\WebApplicationTest1\Default.aspx.cs 101 61 WebApplicationTest1

我認爲我應該重新安排或重新編碼「中選擇新的{。。。」?

protected List<personel> GetPersonalsData2() 
{ 
    List<personel> personeller; 
    using (FirmaEntities firmactx = new FirmaEntities()) 
    { 
     personeller = (from p in firmactx.Personals 
         select new { p.ID, p.Name, p.SurName }); 
     return personeller.ToList(); 
    } 
} 

public class personel 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public string SurName { get; set; } 
} 

回答

4

這部分是返回一個匿名類型:

personeller = (from p in firmactx.Personals select new { p.ID, p.Name, p.SurName }); 
return personeller.ToList(); 

它需要:

personeller = (from p in firmactx.Personals 
       select new personel { Id = p.ID, 
            Name = p.Name, 
            SurName = p.SurName }).ToList(); 

或者,如果該集合是personal類型的已經,你可以這樣做:

personeller = (from p in firmactx.Personals select p).ToList(); 

或,只是這樣的:

personeller = firmactx.Personals.ToList(); 

在您發佈的代碼,它試圖(從IQueryable的,直接在另一無效的轉換)返回List<yourAnonymousType>代替List<personal>,不能在兩者之間轉換,你需要處理同樣類型。

+0

Nick;謝謝你的帖子,但我需要Personels entites的p.ID,p.Name,p.SurName值,所以我寫了新班級personel類。所以我應該返回值列表類型.... – programmerist 2010-04-04 13:14:19

+0

@programmerist - 在這種情況下,使用我的第一個選項,「它需要:」後。只需調用'return personeller;'然後,不需要第二個'.ToList()'。 – 2010-04-04 13:19:31

相關問題