Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 5 and XElement fields

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; }
}
like image 560
Brendan Avatar asked Jun 05 '12 20:06

Brendan


1 Answers

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
like image 169
Ladislav Mrnka Avatar answered Oct 16 '22 03:10

Ladislav Mrnka