2017-06-29 81 views
-1

我使用此代码从EntityFrameWork中的数据库中加载数据,但它向我显示此错误。在LINQ中使用Select Statment

实体或复杂类型'DatabaseModel.State'不能在LINQ to Entities查询中构造。

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(); 
+0

你已经有一个状态对象。你为什么试图再次创建它*?按照Select(state => state)的方式返回'states'对象,或者完全省略'Select'语句'返回db.States.Where(谓词);'。你是否想要省略某些属性? –

回答

1

不能创建项目到由EF一个实体,使用匿名类型,而不是:

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

然后,您可以使用另一种选择,以创建物化后的State实例您的数据使用ToList()

另一种选择是创建一个类(一个DTO)为例,并在您的投影语句中使用。

+0

或者干脆省略'选择'。这个'状态'对象*是*一个'状态' –