moonlander
moonlander

Reputation: 153

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.

Regularly i'd create my tables, and then use Linq to SQL to generate all my classes. 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. 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? And keep the original type for my serialized properties in the Linq auto-generated classes?

A Class for example

Notice that classBProp is of type 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. So Linq to SQL generates the class with a string property.

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

Upvotes: 0

Views: 386

Answers (1)

JuanR
JuanR

Reputation: 7783

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.

So:

  1. ClassA will have a property of type ClassB.
  2. ClassC will be the actual linq class. It looks just like ClassA, except it does not have a property of type ClassB but rather a field of type string.
  3. When saving, map ClassA to ClassC. This is where you serialize ClassB as Xml.
  4. When reading, map ClassC to ClassA. This is where you deserialize xml as ClassB.

I hope that helps.

Upvotes: 1

Related Questions