将项目泛型类型转换为KeyValuePair

时间:2010-08-24 17:10:23

标签: c# linq-to-sql generics

我确定我要做的事情相当简单,但我正在努力。我只是想将IQueryable投影到一个键值对。

这是我班级的一部分:

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 };
}

我从单元测试中调用它。

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

这是PopulateDropDownList方法

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

当我运行单元测试时,它没有任何问题。但是当我对LINQ to SQL执行时,我收到错误:

  

方法'Int32 Invoke(L2S_DomainModel.Entities.Medium)'没有支持的SQL转换。

1 个答案:

答案 0 :(得分:0)

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 };    
}