【问题标题】:SelectListItem and linq any and select statementSelectListItem 和 linq any 和 select 语句
【发布时间】:2015-12-08 13:47:46
【问题描述】:

我的 CarFormat 对象具有 Name 和 Id 属性。我正在获取 ClientId 等于我在方法内部传递的所有格式。我就是这样的

 var carFormats = this.carRepository.All()
                .Where(x => x.CarFormat.Any(c => c.Car.Id == someVar.CarId))
                .Select(x=>x.CarFormat).AsEnumerable();

这会返回一个 CarFormat 对象列表。

此对象具有属性NameId。在我的视图模型中添加 SelectListItem CarFormats 作为属性后,我尝试将这个可枚举的资源列表绑定到选择列表中

myViewModel.CarFormats = new SelectList(carFormats, "Id", "Name");

但我收到数据绑定异常 DataBinding: `

'System.Collections.ObjectModel.ReadOnlyCollection1[[xxxxx, xxxxxx, 版本=1.0.0.0,文化=中性,PublicKeyToken=null]]' 没有 包含名为“Name”的属性。

当我预测只使用列表中的第一项时,一切正常,除了我需要对所有对象使用它,而不仅仅是第一个

myViewModel.CarFormats = new SelectList(carFormats.First(), "Id", "Name");

【问题讨论】:

  • 您正在返回一个包含 ReadOnlyCollections 的可枚举,也许您的意思是在 x.CarFormat 中获取实际的汽车?那么可能需要 SelectMany
  • 在您的 linq 查询中x.CarFormat 是什么类型。您正在使用Any。然后你选择它。我认为这是某种列表。所以你的结果是一个列表的集合。

标签: c# .net linq


【解决方案1】:

将您的查询更改为

 var carFormats = this.carRepository.All()
            .Where(x => x.CarFormat.Any(c => c.Car.Id == someVar.CarId))
            .SelectMany(x=>x.CarFormat).AsEnumerable(); 

使用 SelectMany

一些资源

【讨论】:

    【解决方案2】:

    您的类中的属性是单个选择列表项:

    SelectListItem CarFormats
    

    这就是当您在集合上调用 .First() 时它起作用的原因。

    您正在尝试将其设置为多个项目的值:

    myViewModel.CarFormats = new SelectList(carFormats, "Id", "Name");
    

    将视图模型类中的属性设置为选择列表:

    public SelectList CarFormats { get; set; }
    

    【讨论】:

      【解决方案3】:

      我认为你只是缺少一个 .ToList()

      myViewModel.CarFormats = new SelectList(carFormats.ToList(), "Id", "Name");

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-13
        • 1970-01-01
        • 2021-01-30
        相关资源
        最近更新 更多