I have two classes. I want to map Class1 to a database table with linq to sql.
[Table(Name = "SomeTable")]
public class Class1
{
public Class2 Class2
{
get;
set;
}
}
class Class2
{
public string Name1
{
get;
set;
}
public string Name2
{
get;
set;
}
public string Name3
{
get;
set;
}
}
Database table has 3 columns corresponding to the Name-properties of Class2. In NHibernate f.ex., I would use a ‘component’-element in the xml-mapping, but how to do with linq to sql?
As far as I know, LINQ to SQL doesn’t allow this. But as almost always there are several workarounds for it.
The first one is to create a column-per-complex type property. See Complex Types in LINQ-to-SQL—Reloaded article for more details.
The second one is to associate class
Class2with a table and add a reference to it inClass1(primary/foreign key).And the last one is to store
Class2property of a typeClass2serialized. In theSomeTableit could be a column of typenvarchar(MAX)if you preferJavaScriptSerializeror e.g.xmlif you prefer serialization to XML.Your complex type is pretty simple, so I show an example of how to do it by using
JavaScriptSerializer. We should add a fake property of typeClass2, and a private property of typestringwhich will actually store the serialized value:The
OnLoadedis called after data is loaded by LINQ to SQL, andOnValidateis called before the code is saved – it’s the best place for serializing/deserializing (note, that serialization occurs only on saving, and deserialization on entity load).