views:

42

answers:

1

I'm sure what I'm trying to do is fairly simple but I'm struggling. I simply want to project an IQueryable into a key value pair.

This is part of my class:

public DropDownListActionResult(IQueryable<T> dataItems, Func<T, int> keySelector, Func<T, string> valueSelector, int? selectedID)
{
    _dataItems = dataItems;
    _keySelector = keySelector;
    _valueSelector = valueSelector;
    _selectedID = selectedID;
}

public ActionResult Result()
{
    var items = _dataItems.Select(item =>
                new KeyValuePair<int, string>(_keySelector.Invoke(item), _valueSelector.Invoke(item)))
                .OrderBy("Value")
                .ToList();
    items.Insert(0, new KeyValuePair<int, string>(0, ""));

    var list = new SelectList(items, "Key", "Value", _selectedID);

    return new JsonResult { Data = list, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

And I invoke it like so from a unit test.

    var _stubRepository = MockRepository.GenerateStub<IGalleryRepository>();
    _stubRepository.Stub(x => x.Mediums).Return((
        new[] { 
        new Medium { MediumID = 1,  MediumDescription = "Medium A"},
        new Medium { MediumID = 2,  MediumDescription = "Medium B"},
    }).AsQueryable());

    _controller = new MediumController(_stubRepository, null, null);

    var z = _controller.PopulateDropDownList(-1) as DropDownListActionResult<Medium>;
    var result = z.Result();
    Assert.IsInstanceOf<JsonResult>(result);

This is the PopulateDropDownList method

public ActionResult PopulateDropDownList(int? ID)
{
    return new DropDownListActionResult<Medium>(_repository.Mediums,
                                                x => x.MediumID,
                                                x => x.MediumDescription, ID);
}

When I run the unit test it passes no problem. But when I execute against LINQ to SQL, I get the error:

Method 'Int32 Invoke(L2S_DomainModel.Entities.Medium)' has no supported translation to SQL.

A: 
public DropDownListActionResult(IQueryable<T> dataItems, Expression<Func<T, int>> keySelector, Expression<Func<T, string>> valueSelector, int? selectedID)
{
    _dataItems = dataItems;
    _keySelector = keySelector;
    _valueSelector = valueSelector;
    _selectedID = selectedID;
}

public ActionResult Result()
{    
    var items = _dataItems.Select(item => 
                new KeyValuePair<int, string>(_keySelector.Compile().Invoke(item), _valueSelector.Compile().Invoke(item)))
                .ToDictionary(item => item.Key, item => item.Value);

    items.Add(0, "");

    var list = new SelectList(items.OrderBy(i => i.Value), "Key", "Value", _selectedID);

    return new JsonResult { Data = list, JsonRequestBehavior = JsonRequestBehavior.AllowGet };    
}
Simon Lomax