【问题标题】:Why EF code is not selecting a single column?为什么 EF 代码不选择单列?
【发布时间】:2019-04-02 18:27:11
【问题描述】:

我已经使用它从集合中仅选择一列,但它没有并引发转换错误。

ClientsDAL ClientsDAL = new DAL.ClientsDAL();
var clientsCollection= ClientsDAL.GetClientsCollection();
var projectNum = clientsCollection.Where(p => p.ID == edit.Clients_ID).Select(p => p.ProjectNo).ToString();

方法:

public IEnumerable<Clients> GetClientsCollection(string name = "")
{
    IEnumerable<Clients> ClientsCollection;
    var query = uow.ClientsRepository.GetQueryable().AsQueryable();
    if (!string.IsNullOrEmpty(name))
    {
        query = query.Where(x => x.Name.Contains(name));
    }

    ClientsCollection = (IEnumerable<Clients>)query;
    return ClientsCollection;
}

【问题讨论】:

  • 首先,将 IQueryable 转换为 IEnumerable 将失败。请改用 .AsEnumerable。其次,您选择的属性 clientsCollection.Where(p => p.ID == edit.Clients_ID).Select(p => p.ProjectNo) 是 IQueryable 类型(其中 T 是 ProjectNo 的类型),所以 .此属性上的 ToString() 将始终只返回类型(除非您为此创建了扩展方法)
  • 我认为你需要FirstFirstOrDefault 而不是Select(..).ToString()
  • 另外,请注意,通过将 IQueryable 强制转换为该类型的 IEnumerable,您正在隐式枚举查询并因此具体化结果。
  • @AleksAndreev 把它放在答案框中,我会标记它。也感谢其他人完成
  • @JohnnyShallow 完成。请注意,我没有测试过它(就像我通常做的那样),但我希望这个想法很清楚

标签: c# asp.net-mvc entity-framework


【解决方案1】:

正如 DevilSuichiro 在 cmets 中所说,您不应该转换为 IEnumerable&lt;T&gt; 只需调用 .AsEnumerable() 它会保持懒惰。

但在您的情况下,您似乎根本不需要它,因为 FirstFirstOrDefault 也可以与 IQueryable 一起使用。

要获得单个字段,请使用此代码

clientsCollection
  .Where(p => p.ID == edit.Clients_ID)
  .Select(p => p.ProjectNo)
  .First() // if you sure that at least one item exists

或者(更安全)

var projectNum = clientsCollection
  .Where(p => p.ID == edit.Clients_ID)
  .Select(p => (int?)p.ProjectNo)
  .FirstOrDefault();

if (projectNum != null)
{
    // you find that number
}
else
{
    // there is no item with such edit.Clients_ID
}

甚至更简单的零传播

var projectNum = clientsCollection
  .FirstOrDefault(p => p.ID == edit.Clients_ID)?.ProjectNo;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    • 1970-01-01
    • 2012-04-11
    • 2019-08-28
    • 2012-10-29
    • 2011-07-09
    • 1970-01-01
    相关资源
    最近更新 更多