简体   繁体   English

C#-使用Linq to SQL和XML序列化

[英]C# - Using Linq to SQL with XML Serialization

There is something i don't quite understand when using Linq to SQL and XML serialization on some of my object's properties. 在对象的某些属性上使用Linq进行SQL和XML序列化时,我不太了解。

Regularly i'd create my tables, and then use Linq to SQL to generate all my classes. 我会定期创建表,然后使用Linq到SQL生成我的所有类。 But now since i serialize some of my classes properties, when creating the database tables, i define these properties as varchar (for the XML string) instead of the actual type that they are. 但是现在由于我序列化了一些类属性,因此在创建数据库表时,我将这些属性定义为varchar(用于XML字符串),而不是它们的实际类型。 So the auto-generated classes are created with string typed properties instead of the actual classes. 因此,将使用字符串类型的属性而不是实际的类来创建自动生成的类。

Is there a way to tell Linq to apply my de/serialization automatically when inserting/fetching objects from the database? 当从数据库中插入/获取对象时,有没有办法告诉Linq自动应用我的反序列化? And keep the original type for my serialized properties in the Linq auto-generated classes? 并在Linq自动生成的类中保留序列化属性的原始类型?

A Class for example 例如一个类

Notice that classBProp is of type ClassB. 注意classBProp的类型为ClassB。

class ClassA
{
    private string name;
    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    private ClassB classBProp; // <-- This is something i'm serializing
    public ClassB ClassBProp
    {
        get { return classBProp; }
        set { classBProp = value; }
    }

    public ClassA()
    {
        classBProp = new ClassB();
    }
}

The table for the class 上课表

Here ClassBProp is of type varchar. 这里ClassBProp是varchar类型的。 So Linq to SQL generates the class with a string property. 因此,Linq to SQL生成具有字符串属性的类。

CREATE TABLE [dbo].[ClassA] (
[Id]         INT           NOT NULL,
[Name]       VARCHAR (50)  NULL,
[ClassBProp] VARCHAR (MAX) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);

I don't think this is possible. 我认为这是不可能的。

For situations like this you would have to use another object that hides the fact that you are storing the object as an Xml string. 在这种情况下,您将不得不使用另一个对象来隐藏将对象存储为Xml字符串这一事实。

So: 所以:

  1. ClassA will have a property of type ClassB. ClassA将具有ClassB类型的属性。
  2. ClassC will be the actual linq class. ClassC将是实际的linq类。 It looks just like ClassA, except it does not have a property of type ClassB but rather a field of type string. 它看起来与ClassA相似,只是它不具有ClassB类型的属性,而是一个string类型的字段。
  3. When saving, map ClassA to ClassC. 保存时,将ClassA映射到ClassC。 This is where you serialize ClassB as Xml. 在这里您可以将ClassB序列化为Xml。
  4. When reading, map ClassC to ClassA. 阅读时,将ClassC映射到ClassA。 This is where you deserialize xml as ClassB. 在此将xml反序列化为ClassB。

I hope that helps. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM