Entity Framework 5 and XElement fields

c#, entity-framework, entity-framework-5, xelement, xml

Solution

In principle there is no better way. You need two properties - one for `XElement` and one for backing persisted string. If you want to reduce amount of parsing and conversion you need to implement some infrastructure for that. General approach would be:

- Handle `ObjectContext.ObjectMaterialized` event - if the materialized object is `MyEFEntity` parse string and save it to `XElement` property. If you are using `DbContext` you can still get `ObjectContext` through its explicitly implemented `IObjectContextAdapter`.

- Override `SaveChanges` - in the method find all modified or inserted instances of `MyEFEntity` through `DbContext.ChangeTracker.GetEntries` and save their XML to string property

Problem

Started playing with Visual Studio 2012 RC and Entity Framework 5... absolutely loving it but wondering if there's a cleaner way to do this. I would like to cut out the middle-man of parsing the XML every time, and setting it via .ToString() ``` public class MyEFEntity { [NotMapped()] public XElement Tags { get { return XElement.Parse(tags); } set { tags = value.ToString(); } } [Column("Tags", TypeName = "xml"), Required] public string tags { get; set; } } ```

Original source