1

我遇到了 EF 和 xml 反序列化的问题。我设法在 xml 文件中序列化 EF 对象,但我被这些文件的反序列​​化所困扰。

我的序列化功能:

public static void SerializeIntoFile(object inputObject, string fileName)
{
    DataContractSerializer serializer = new DataContractSerializer(typeof(Form));

    using (XmlWriter wr = XmlWriter.Create(new StringBuilder(fileName)))
    {
        serializer.WriteObject(wr, inputObject);
    }
}

我的反序列化功能:

 public static T DeserializeFromStream<T>(Stream stream)
    {
        DataContractSerializer dataContract = new DataContractSerializer(typeof(Form));
        return (T)dataContract.ReadObject(stream);
    }

此函数在 silverlight 中使用此函数调用:

private void FilePicker(object sender, System.Windows.RoutedEventArgs e)
{
    var filepicker = new OpenFileDialog();
    bool? userClickedOK = filepicker.ShowDialog();
    if (userClickedOK == true)
    {
        var form = SerialisationHelper.DeserializeFromStream<Form>(filepicker.File.OpenRead());
    }
}

和输入 xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<Form xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" xmlns="http://schemas.datacontract.org/2004/07/SuiviAT.WebService.EFModel">
    <EntityKey xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Data" z:Id="i2" xmlns="http://schemas.datacontract.org/2004/07/System.Data.Objects.DataClasses">
        <d2p1:EntityContainerName>
            SuiviATModelContainer
        </d2p1:EntityContainerName>
        <d2p1:EntityKeyValues i:nil="true" />
        <d2p1:EntitySetName>
            FormSet
        </d2p1:EntitySetName>
    </EntityKey>
    <Id>
        0
    </Id>
    <Rows>
        <Row z:Id="i3">
            <EntityKey xmlns:d4p1="http://schemas.datacontract.org/2004/07/System.Data" z:Id="i4" xmlns="http://schemas.datacontract.org/2004/07/System.Data.Objects.DataClasses">
                <d4p1:EntityContainerName>
                    SuiviATModelContainer
                </d4p1:EntityContainerName>
                <d4p1:EntityKeyValues i:nil="true" />
                <d4p1:EntitySetName>
                    RowSet
                </d4p1:EntitySetName>
            </EntityKey>
            <Form z:Ref="i1" />
            <FormId>
                0
            </FormId>
            <FormReference xmlns:d4p1="http://schemas.datacontract.org/2004/07/System.Data.Objects.DataClasses">
                <d4p1:EntityKey xmlns:d5p1="http://schemas.datacontract.org/2004/07/System.Data" i:nil="true" />
            </FormReference>
            <Id>
                0
            </Id>
            <Label>
                Couleur
            </Label>
            <Type>
                String
            </Type>
            <Value>
                Bleu
            </Value>
        </Row>
    </Rows>
</Form>

反序列化后返回的对象是 children null 我不知道为什么......

如果有人可以帮助我,将不胜感激!

谢谢!

4

0 回答 0