【问题标题】:Use Select Statment in LINQ [duplicate]在 LINQ 中使用 Select 语句
【发布时间】:2017-06-29 19:41:02
【问题描述】:

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

无法在 LINQ to Entities 查询中构造实体或复杂类型“DatabaseModel.State”。

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

【问题讨论】:

  • 您已经有一个 State 对象。你为什么要再次创建它?要么按原样返回states 对象Select(state =&gt; state),要么完全省略Select 语句return db.States.Where(predicate);。您是否尝试省略一些属性?

标签: c# entity-framework linq


【解决方案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()

在使用 ToList() 实现数据后,您可以使用另一个 Select 创建 State 的实例

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

【讨论】:

  • 或者干脆省略Selectstates 对象 State
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多