Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify SQL Server XML data type in Entity Frameworks 4.0 Model?

I'm building an ORM using Entity Frameworks 4.0 (CTP5) in the Model-First pattern. A few of my entities have complex (object tree) properties that don't need to be ORM entities - they're only of interest to back-end server systems that use this database, not to the clients that use this database.

I could just serialize the property's object tree down to a string and store it in the DB as a string, but the SQL Server XML data type is really appealing. To be able to query over the XML data contents in an intelligent manner would be very nice.

However, I don't see any way to specify that I want an XML data type in the Visual Studio Entity Modeler.

Is the only way to get this done to specify string fields in the model, emit the DDL, then modify the DDL to change the string fields to XML fields? That seems awfully brittle and write-once, change never. Is there a better way?

like image 945
dthorpe Avatar asked Feb 28 '11 23:02

dthorpe


1 Answers

In "Entity Framework 4.0 Recipes", Larry Tenny and Zeeshan Hirani state that XML data types are simply not supported by EF 4.0.

They do offer a workaround, which is to make the string type property on the entity class generated by the model private and create a new property (in your own partial class of the entity class) to return an XElement from the internal string property:

public partial class Candidate
{
    private XElement candidateResume = null;

    public XElement CandidateResume
    {
        get 
        {
            if (candidateResume == null)
            {
                candidateResume = XElement.Parse(this.Resume);
                candidateResume.Changed += (s,e) =>
                {
                    this.Resume = candidateResume.ToString();
                }
            }

            return candidateResume;
        }

        set
        {
            candidateResume = value;
            candidateResume.Changed += (s,e) =>
            {
                this.Resume = candidateResume.ToString();
            }
            this.Resume = value.ToString();
        }
    }
}

Creating a shadow property of the desired XML type like this should work, but the conversion between string and XML on every change of the original string property (Resume) and the new shadow property (CandidateResume) is pretty expensive.

If anyone has any better ideas, I'm still open to suggestions.

like image 175
dthorpe Avatar answered Oct 30 '22 07:10

dthorpe