且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

数据契约序列化复杂类型

更新时间:2022-05-14 18:14:24

通过修饰数据类为 DataContract ,你是天生的设置结构(XML,JSON等),其该数据将被重新psented当它被序列$ P $

By decorating data classes as DataContract, you are inherently setting the structure (Xml, Json etc) that the data will be represented as when it is serialized.

我可以建议你拆分业务实体和序列化实体'出你的数据类,如关注的问题如果 + 酒吧是你的数据存储或ORM重新presentations,然后删除 [DataContract] - 从他们的:

Can I suggest that you split the concerns of 'Business Entity' and 'Serialization Entity' out of your data classes, e.g. if Foo + Bar are your in memory or ORM representations of the data, then remove the [DataContract]s from them:

public partial class Foo
{
    public string MyString { get; set; }
    public int MyInt { get; set; }
    public Bar MyBar { get; set; }
}

public class Bar
{
    public string BarField { get; set; }
}

于是,专门为序列化格式,再配以 DataContract

[DataContract]
public partial class SerializableFoo
{
    [DataMember]
    public string MyString { get; set; }
    [DataMember]
    public int MyInt { get; set; }
    [DataMember]
    public string MyBar { get; set; }
}

,然后提供的映射功能,从一个到另一个地图。 LINQ是真棒对于这样的工作,如果类具有大致相同属性名称,然后AutoMapper能为你做了很多的工作。

And then provide a mapping function to map from the one to the other. LINQ is awesome for this kind of work, and if the classes have mostly the same property names, then AutoMapper can do a lot of the work for you

例如。

var wireFoo = new SerializableFoo()
{
    MyString = foo.MyString,
    MyInt = foo.MyInt,
    MyBar = foo.Bar.BarField // Do the projection / flattening here
}
// Serialize wireFoo here, or return it from a WCF Service, etc.