没有DataMember属性的DataContract序列化 [英] DataContract Serialization without DataMember Attribute

查看:118
本文介绍了没有DataMember属性的DataContract序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用FreezeAllAccountsForUser函数生成了以下XML.我只需要序列化此功能的以下两列.如何将序列化限制为两列?

I have the following XML generated using a function FreezeAllAccountsForUser. I need to serialize only the following two columns for this function. How can I restrict the serialization to two columns?

  1. BankAccountID
  2. 状态

注意:关键点在于,进行此限制的作用域应该仅在FreezeAllAccountsForUser函数内; 非全局.

Note: The key point is that the scope of making this restriction should be only within the function FreezeAllAccountsForUser; not global.

参考

  1. 序列化IEnumerable包含派生类:循环引用问题

XML

 <ArrayOfBankAccount xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="1" z:Size="1" 
                xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" 
                xmlns="http://schemas.datacontract.org/2004/07/DBML_Project">

  <BankAccount z:Id="2" i:type="FixedBankAccount">

<AccountOwnerID>2</AccountOwnerID>
<AccountType z:Id="3">Fixed     </AccountType>
<BankAccountID>2</BankAccountID>

<BankUser z:Id="4">
  <BankAccounts z:Id="5" z:Size="1">
    <BankAccount z:Ref="2" i:nil="true" />
  </BankAccounts>
  <Name z:Id="6">TestP1    </Name>
  <UserID>2</UserID>
  <UserType z:Id="7">Ordinary  </UserType>
</BankUser>

<OpenedDate i:nil="true" />

<Status z:Id="8">FrozenFA</Status>

   </BankAccount>

</ArrayOfBankAccount>

序列化

public class BankAccountAppService
{
    public RepositoryLayer.ILijosBankRepository AccountRepository { get; set; }

    public void FreezeAllAccountsForUser(int userId)
    {
        IEnumerable<DBML_Project.BankAccount> accounts = AccountRepository.GetAllAccountsForUser(userId);
        foreach (DBML_Project.BankAccount acc in accounts)
        {

            string typeResult = Convert.ToString(acc.GetType());
            string baseValue = Convert.ToString(typeof(DBML_Project.BankAccount));

            if (String.Equals(typeResult, baseValue))
            {
                throw new Exception("Not correct derived type");
            }

            acc.Freeze();
        }



        System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
        System.Xml.XPath.XPathNavigator nav = xmlDoc.CreateNavigator();

        using (System.Xml.XmlWriter writer = nav.AppendChild())
        {
            System.Runtime.Serialization.DataContractSerializer serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(List<DBML_Project.BankAccount>), null, int.MaxValue, false, true, null);
            serializer.WriteObject(writer, accounts);
        }

        xmlDoc.Save("C:\\DevTEST\\FileName.txt");



    }

}

域类

namespace DBML_Project
{
[KnownType(typeof(FixedBankAccount))]
[KnownType(typeof(SavingsBankAccount))]
public  partial class BankAccount
{
    //Define the domain behaviors
    public virtual void Freeze()
    {
        //Do nothing
    }
}

public class FixedBankAccount : BankAccount
{

    public override void Freeze()
    {
        this.Status = "FrozenFA";
    }
}

public class SavingsBankAccount : BankAccount
{

    public override void Freeze()
    {
        this.Status = "FrozenSB";
    }
}  
}

LINQ to SQL自动生成的类

Auto generated Class by LINQ to SQL

[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.BankAccount")]
[InheritanceMapping(Code = "Fixed", Type = typeof(FixedBankAccount), IsDefault = true)]
[InheritanceMapping(Code = "Savings", Type = typeof(SavingsBankAccount))]
public partial class BankAccount : INotifyPropertyChanging, INotifyPropertyChanged

推荐答案

听到这将是令人烦恼的(我知道您在两个序列化器之间一直处于弹跳状态),但是:XmlSerializer 确实如此支持两种方式:a)使用XmlAttributeOverrides在运行时指定属性,以及b)通过条件序列化"(对于成员Foopublic bool ShouldSerializeFoo()). DataContractSerializer都不支持这些.不同的序列化器:不同的功能.

This is going to be vexing to hear (I know you've been bouncing between the two serializers), but: XmlSerializer does support that, in two ways: a) by using XmlAttributeOverrides to specify the attributes at runtime, and b) by way of "conditional serialization" (public bool ShouldSerializeFoo() for member Foo). DataContractSerializer supports neither of these. Different serializers: different features.

我的建议:停止尝试将序列化适合您的域模型. 可以起作用,但是一旦出现混乱停止战斗,并创建一个简单的单独的DTO模型即可,其主要目的是序列化 ,然后根据需要在域模型和DTO模型之间进行映射.

My advice: stop trying to fit serialization into your domain model. That can work, but the moment it gets messy stop fighting it, and create a separate DTO model that is simple, designed to be serialized as it's primary purpose, and just map between the domain model and the DTO model as required.

这篇关于没有DataMember属性的DataContract序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆