当前位置: 代码迷 >> .NET Framework >> EF6 Code First+WCF 复杂类型序列化出错
  详细解决方案

EF6 Code First+WCF 复杂类型序列化出错

热度:467   发布时间:2016-05-01 23:31:36.0
EF6 Code First+WCF 复杂类型序列化报错
我有两张表Product和Type,它们之间存在引用关系。WCF是使用EF是实体作为DataContract的。EF实体代码如下:

Product:
public partial class Product
  {
     public int ID { get; set; }
 
     [Required]
     [StringLength(50)]
     public string Code { get; set; }
 
     public int TypeID { get; set; }
 
     public double Price { get; set; }
 
     public string Description { get; set; }
 
     public DateTime PublishDate { get; set; }
 
     public virtual ProductType ProductType { get; set; }
 }


ProductType:
public partial class ProductType
 {
     public ProductType()
     {
         Product = new HashSet<Product>();
     }
 
     public int ID { get; set; }
 
     [Required]
     [StringLength(50)]
     public string Name { get; set; }
 
     public virtual ICollection<Product> Product { get; set; }
 }


在调用WCF时会发生异常:


我试过如果把两个表之间的关系去掉,让两个实体类不存在循环引用的话,就没问题。
------解决思路----------------------

public partial class Product
  {
     public int ID { get; set; }
  
     [Required]
     [StringLength(50)]
     public string Code { get; set; }
  
     public int TypeID { get; set; }
  
     public double Price { get; set; }
  
     public string Description { get; set; }
  
     public DateTime PublishDate { get; set; }
  
     //public virtual ProductType ProductType { get; set; },在这里把ProductType类型要描述的属性用其他形式来描述
 }

public partial class ProductType
 {
     public ProductType()
     {
         Product = new HashSet<Product>();
     }
 
     public int ID { get; set; }
 
     [Required]
     [StringLength(50)]
     public string Name { get; set; }
 
     public virtual ICollection<Product> Product { get; set; }
 }

------解决思路----------------------
还有这样设计程序代码的?这在逻辑上就是无休止地死掉了啊。

如果你一定要这样写,那么至少有一端是“延迟加载的”。也就是说运行时才动态加载,而不是在对象实例化时加载。
------解决思路----------------------
会报告循环引用错误才对,怎么报告超时?

EF 实体用作wcf传输是忌讳,不符合规范。

class 头顶加上  [DataContract(IsReference=true)]  就行了。
------解决思路----------------------
还是老老实实定义一套没有循环引用关系的模型吧。

ef本身是动态代理,也就是其实传输的根本不是“product”而是它产生的一个动态类型,你对它的序列化完全是失控的。
  相关解决方案