我正在使用实体框架,我发现它无法序列化 EDM 对象的输出。现在我正在使用 Northwind Products-table。因此,我被迫将对象转换为另一个对象并使用 .Cast 但它不起作用。我唯一的解决方案是逐个属性在我的代码中手动执行,但我在想 - 必须有更好的方法!看在上帝的份上——现在是 2013 年!这个实体一开始似乎是个好主意,但它有很多陷阱和限制,实际上阻碍大于帮助,但无论如何 EDMX 图都不错!
谁有更好的解决方案来铸造物体?
POCO
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
//public Nullable<int> SupplierID { get; set; }
//public Nullable<int> CategoryID { get; set; }
public string QuantityPerUnit { get; set; }
public Nullable<decimal> UnitPrice { get; set; }
public Nullable<short> UnitsInStock { get; set; }
public Nullable<short> UnitsOnOrder { get; set; }
public Nullable<short> ReorderLevel { get; set; }
//public bool Discontinued { get; set; }
public Category Category { get; set; }
//public ICollection<Order_Detail> Order_Details { get; set; }
//public Supplier Supplier { get; set; }
}
查看模型
public class ProductsViewModel
{
public List<POCO.Product> Products { get; set; }
public ProductsViewModel()
{
using (NorthwindEntities dNorthwindEntities = new NorthwindEntities())
{
this.Products = dNorthwindEntities.Products.Cast<POCO.Product>().ToList();
Web API 控制器:
public class ProductsController : ApiController
{
public List<Product> GetAllProducts()
{
var viewmodel = new ProductsViewModel();
return viewmodel.Products;
}