开发者

How can I write list type returning value in Linq with Entity Framework?

开发者 https://www.devze.com 2022-12-25 20:32 出处:网络
How can I return List<personel> data type from below procedure. If开发者_运维百科 I press F5 it throw me this error:

How can I return List<personel> data type from below procedure. If开发者_运维百科 I press F5 it throw me this error:

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

I think that I should rearrange or recode "select new {. . . . " ?

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; }
 }


This part is returning an anonymous type:

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

It needs to be:

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

Or if that collection is of type personal already, you can do this:

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

Or, just this:

personeller = firmactx.Personals.ToList();

In your posted code it's trying to return List<yourAnonymousType> (directly from the IQueryable, another invalid cast) instead of List<personal> and can't convert between the two, you need to be dealing with the same type.

0

精彩评论

暂无评论...
验证码 换一张
取 消