1

Hi All i am facing above error. I want retrieve only two columns from database using edmx. While running i get following error:

"cannot initialize type with a collection initializer because it does not implement ienumerable."

using (DBEntities context = new DBEntities())
{
    IList<myData> objData = null;
    objData = context.EDatas
        .Where(entity => entity.Status == 0 && entity.Id == Id)
        .Select(entity => new myData
        { 
            entity.ID, 
            entity.Key                          
        }).ToList();                  
}
Tim Schmelter
  • 411,418
  • 61
  • 614
  • 859
Santosh Singh
  • 11
  • 1
  • 6

2 Answers2

3

Instead of

.Select(entity => new myData
{ 
    entity.ID, 
    entity.Key                          
})

You need to use the correct property names of myData:

.Select(entity => new myData
{ 
    ID = entity.ID, 
    Key = entity.Key                          
})

otherwise the compiler assumes that you want to fill a collection.

Tim Schmelter
  • 411,418
  • 61
  • 614
  • 859
  • I have tried this it gives below error "The entity or complex type 'DBModel.myData' cannot be constructed in a LINQ to Entities query" – Santosh Singh Aug 06 '14 at 11:08
  • @SantoshSingh: i'm not familiar with L2E, here is the reason and the solution: http://stackoverflow.com/questions/5325797/the-entity-cannot-be-constructed-in-a-linq-to-entities-query – Tim Schmelter Aug 06 '14 at 11:10
0

You are not creating an anonymous type, and compiler thinks that you are creating a collection using collection initializer syntax. You should use the property names and set values like this:

.Select(entity => new myData
                  { 
                       Id = entity.ID, 
                       Key = entity.Key                          
                  }).ToList();  
Selman Genç
  • 94,267
  • 13
  • 106
  • 172