我是Azure Service Fabric的新手,并在Pluralsight上观看了Ivan Gavryliuk的“了解Azure Service Fabric的编程模型”课程。我一直在遵循,并且在本课程中说明了可靠服务和API的基本数据模型。
但是,如果我增加了所用数据模型的复杂性,则会出错。
来自ECommerce.ProductCatelog.Model的Product.cs
namespace ECommerce.ProductCatalog.Model
{
public class Product
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public double Price { get; set; }
public int Availability { get; set; }
public Supplier Suppliers { get; set; }
}
public class Supplier
{
public Guid Id { get; set; }
public string Name { get; set; }
}
}
来自ECommerce.API.Model的ApiProduct.cs
public class ApiProduct
{
[JsonProperty("id")]
public Guid Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("price")]
public double Price { get; set; }
[JsonProperty("isAvailable")]
public bool IsAvailable { get; set; }
[JsonProperty("suppliers")]
public ApiSupplier suppliers { get; set; }
}
public class ApiSupplier
{
[JsonProperty("id")]
public Guid Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
来自Ecommerce.API.Controlers的ProductController.cs
[HttpGet]
public async Task<IEnumerable<ApiProduct>> GetAsync()
{
IEnumerable<Product> allProducts = await _service.GetAllProductsAsync();
return allProducts.Select(p => new ApiProduct
{
Id = p.Id,
Name = p.Name,
Description = p.Description,
Price = p.Price,
IsAvailable = p.Availability > 0,
suppliers = p.Suppliers
});
}
以上块中的最后一行会触发智能感知错误:“无法将类型'ECommerce.ProductCatelog.Model.Supplier'隐式转换为'ECommerce.API.Model.Supplier'”
有关如何解决此欢迎问题的任何建议:)
干杯,亚当
您的问题不是特定于Service Fabric,而是C#。您正在尝试使用其他类型的值设置变量。
在此行:
IEnumerable<Product> allProducts = await _service.GetAllProductsAsync();
您将获得ECommerce.ProductCatalog.Model.Product
类型的项目的集合。在此类中,添加了类型为Suppliers
的属性Supplier
(由于它不是集合,因此应为ECommerce.ProductCatalog.Model.Supplier
。)>
现在,带有以下行:
return allProducts.Select(p => new ApiProduct { Id = p.Id, Name = p.Name, Description = p.Description, Price = p.Price, IsAvailable = p.Availability > 0, suppliers = p.Suppliers });
您正在将该集合转换为新类型
ECommerce.API.Model.Product
的集合,并向其中添加了类型为Suppliers
的新属性ECommerce.API.Model.Supplier
,但是您将此属性设置为原始值,而不进行转换。因此,请将原始Suppliers
属性转换为正确的类型:
return allProducts.Select(p => new ApiProduct
{
Id = p.Id,
Name = p.Name,
Description = p.Description,
Price = p.Price,
IsAvailable = p.Availability > 0,
suppliers = new Supplier
{
Id = p.Suppliers.Id,
Name = p.Suppliers.Name
}
});