我想从.NET API中获取数据,并将其包含在参考中。 但是,严重的是我被异常波纹管卡住了。
Error 2 Cannot implicitly convert type
System.Threading.Tasks.Task<System.Collections.Generic.List<BizCover.Repository.Cars.Car>>
toBizCover.Api.Cars.Model.CarsVM
这是我在API控制器中的代码。
public IHttpActionResult getAllDataCars()
{
CarRepository carRep = new CarRepository();
IHttpActionResult result = null;
try
{
CarsVM dataAPICars = new CarsVM();
dataAPICars = carRep.GetAllCars(); //here's the error return.
if (dataAPICars != null)
{
var a = "ada";
}
else
{
var b = "null";
}
}
catch (Exception ex)
{
var c = ex.ToString();
}
return result;
}
这也是我的模特
public class CarsVM
{
public CarsVM()
{
}
public string Colour { get; set; }
public string CountryManufactured { get; set; }
public int Id { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public decimal Price { get; set; }
public int Year { get; set; }
public CarsVM(string Colour, string CountryManufactured, int Id, string Make, string Model, decimal Price, int Year)
{
this.Colour = Colour;
this.CountryManufactured = CountryManufactured;
this.Id = Id;
this.Make = Make;
this.Model = Model;
this.Price = Price;
this.Year = Year;
}
}
我的目标是我要从参考(CarRepository)获取数据并将其存储在我的模型中。 我不太清楚.NET Framework API应该如何逐步工作以及如何实现等待异步。
First, to fix the
Task
issue, you need to await it, so your method signature needs to change to anasync
method:不用担心-它仍会按预期工作。 ASP.NET知道这是什么。
And then you can
await
the async method that you are calling:现在,这将稍微改变您的名义问题,但仍然会产生essentailly相同的问题:
The problem here is that you have potentially many cars in a list, and you want a single car. Assuming there can only ever be one entry, you can use
SingleOrDefault
:If there can be multiple, but you only want the first / last, you should use
.FirstOrDefault()
or.LastOrDefault()
:如果您想要其他东西,恐怕您必须弄清楚您的汽车清单如何成为一辆汽车。