-1

I use this code to load data from the database in EntityFrameWork, but it shows me this error.

The entity or complex type 'DatabaseModel.State' cannot be constructed in a LINQ to Entities query.

public class StateRepository : BaseRepository
{
    public IQueryable Where(System.Linq.Expressions.Expression<Func<Models.DomainModels.State, bool>> predicate)
    {
        return db.States
            .Where(predicate)
            .Select(states => new State
            {
                Id = states.Id,
                Country_Id = states.Country_Id,
                Name = states.Name,
                PhoneCode = states.PhoneCode
            });
    }
}


var objStateRepository = new StateRepository();
datagrideview1.DataSource = objStateRepository.Where(p => p.Name.Contains(txtSearchState.Text)).ToList();
  • You already have a State object. Why are you trying to create it *again*? Either return the `states` object as is `Select(state => state)`, or omit the `Select` statement entirely `return db.States.Where(predicate);`. Are you trying to *omit* some properties perhaps? – Panagiotis Kanavos Jun 29 '17 at 09:57

1 Answers1

1

You can't create project into an entity that is mapped by EF, use anonymous types instead:

return db.States
            .Where(predicate)
            .Select(states => new
            {
                Id = states.Id,
                Country_Id = states.Country_Id,
                Name = states.Name,
                PhoneCode = states.PhoneCode
            }).ToList()

You can then use another Select to create instances of State after you Materialize your data using ToList()

Another option would be to create a class (a DTO) for example and use in your projection statement.

Zein Makki
  • 29,485
  • 6
  • 52
  • 63