1

My CarFormat object has Name and Id property. I'm fetching all carformats which ClientId is equal to the one I passing inside method. I'm doing like this

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

this returns me a list of CarFormat objects.

This object has properties Name and Id. After I add SelectListItem CarFormats as property inside my viewmodel I tried to bind this enumerable list of resources into select list

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

but I'm getting databinding exception DataBinding: `

'System.Collections.ObjectModel.ReadOnlyCollection1[[xxxxx, xxxxxx, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' does not contain a property with the name 'Name'.

When I projection to use only first item from the list everything works, except I need this for all objects not just first

myViewModel.CarFormats = new SelectList(carFormats.First(), "Id", "Name");
user1765862
  • 13,635
  • 28
  • 115
  • 220
  • 1
    You are returning a enumerable containing of ReadOnlyCollections perhaps you meant to get the actual cars within the x.CarFormat ? Possibly SelectMany is needed then – Dbuggy Dec 08 '15 at 13:55
  • 2
    What type is `x.CarFormat` within your linq query. You are using `Any` on it. and later you select it. I'm thinking it's a list of some sort. so your result is a collection of lists. – Dbuggy Dec 08 '15 at 14:00

3 Answers3

2

Change your query to

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

to use SelectMany

Some resources

Community
  • 1
  • 1
BobRock
  • 3,477
  • 3
  • 31
  • 48
0

The property in your class is a single select list item:

SelectListItem CarFormats

Which is why it works when you call .First() on the collection.

You are trying to set it with a value of multiple items:

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

Set the property in your view model class to a select list:

public SelectList CarFormats { get; set; }
Stephen Brickner
  • 2,584
  • 1
  • 11
  • 19
0

I think you just missing a .ToList()

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