【发布时间】:2015-04-03 06:41:40
【问题描述】:
我有一个在控制器中搜索人的操作,它将返回一个匿名列表:
[UnitOfWork]
[HttpGet, Route("api/Search/People")]
public virtual IHttpActionResult GetResult(string keyword)
{
// ...
var result = peopleList.Select(x => new
{
PersonId = x.Id.Value,
EmploymentNumber = x.EmploymentNumber,
FirstName = x.Name.FirstName,
LastName = x.Name.LastName,
Email = x.Email
});
return Ok(result);
}
下面是方法的测试用例:
[Test]
public void ShouldSearchPeople()
{
// Mocks...
var target = new PeopleSearchController(searchRepository, personRepository, new FakePermissionProvider());
// Error here
var result = (OkNegotiatedContentResult<IEnumerable<dynamic>>)target.GetResult("Ashley");
Assert.NotNull(peopleList);
// Other assert...
}
然后我得到如下错误:
System.InvalidCastException: Unable to cast object of type
'System.Web.Http.Results.OkNegotiatedContentResult`1[System.Collections.Generic.IEnumerable`1[<>f__AnonymousType1e`5[System.String,System.String,System.String,System.Guid,System.String]]]'
to type
'System.Web.Http.Results.OkNegotiatedContentResult`1[System.Collections.Generic.IEnumerable`1[System.Object]]'.
似乎带有类或单个匿名的 IEnumerable 可以用于此类转换,但带有匿名的 IEnumerable 不起作用。
我怎样才能进行这样的转换?谢谢。
【问题讨论】:
-
也许
var result = target.GetResult("Ashley") as OkNegotiatedContentResult<IEnumerable<object>>;在您的测试方法中对您有用...? -
@stefankmitph
result将始终为空。
标签: c# dynamic anonymous-types