0

我正在使用实体框架,我发现它无法序列化 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; 
            }
4

1 回答 1

1

1.您可以使用框架来自动AutoMapper处理映射。EntitiesViewModel / DTO

2. 不推荐使用EntitiesView即使是 POCO 形式),原因如下:

  • Security:将实体发送回客户端/视图可能会暴露比您预期更多的数据。

  • Serialization:由于您的实体通常包含对另一个实体的引用,并且这些实体可能包含对(父)实体的引用,因此您必须配置您的序列化程序来处理这种情况,否则您将得到Circular Dependency Exception.

  • Incompatibility:您的实体结构可能与您view/client需要呈现的内容不兼容。有时您view只需要一个简单string的实体以非常复杂的方式保存这些数据,因此view需要“提取”它,而您最终会view得到一堆不必要的实体向下钻取代码。
于 2013-03-17T11:38:55.077 回答