简体   繁体   中英

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; }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM