ef4 cause Circular reference in web service

前端 未结 3 1168
庸人自扰
庸人自扰 2020-11-29 10:54

I have a Reason object:

public class Reason
{
    public virtual long Id { get; set; }
    public virtual string Name { get; set; }
    public virtual Comp         


        
3条回答
  •  情书的邮戳
    2020-11-29 11:21

    There are multiple solutions for your problem and they really depend on the type of service you are using and on the type of serialization:

    • The clean approach is using DTO (data transfer objects) as @Mikael already suggested. DTO is special object which transfers exactly what you need and nothing more. You can simply create DTOs to not contain circular references and use AutoMapper to map between entities and DTOs and vice versa. +1 for @Mikael because he was the first to mentioned this.

    All other approaches are based on tweeking serialization as @Haz suggested:

    • WCF and DataContractSerializer: explicitly mark your entities with DataContract[IsReference=true] and all properties with [DataMember] attributes. This will allow you to use circular references. If you are using T4 template to generate entities you must modify it to add these attributes for you.
    • WCF and DataContractSerializer: implicit serialization. Mark one of related navigation properties with [IgnoreDataMember] attribute so that property is not serialized.
    • XmlSerializer: mark one fo related navigation properties with [XmlIgnore] attribute
    • Other serializations: mark one of related navigation properties with [NonSerialized] (+1 for Haz he was the first to mention this) for common serialization or [ScriptIgnore] for some JSON related serialization.

提交回复
热议问题