Skip to content

Instantly share code, notes, and snippets.

@RhysC
Created June 30, 2015 02:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RhysC/c7faeac92e7a76b80b2a to your computer and use it in GitHub Desktop.
Save RhysC/c7faeac92e7a76b80b2a to your computer and use it in GitHub Desktop.
EF with XML properties
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="Model" connectionString="data source=(LocalDb)\v11.0;initial catalog=EfWithXmlConsoleApplication.Model;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Data.Entity;
namespace EfWithXmlConsoleApplication
{
class Program
{
private static void Main(string[] args)
{
using (var db = new Model())
{
db.MyEntities.Add(new MyEntity
{
Name = "RhysTest",
Address = new Address
{
StreetLine1 = "17 honey lane",
City = "Wellington",
PostCode = "WashDC",
Country = "UK"
}
});
db.SaveChanges();
}
using (var db = new Model())
{
foreach (var ent in db.MyEntities)
{
Console.WriteLine(ent);
}
}
Console.ReadLine();
}
}
public class Model : DbContext
{
public Model()
: base("name=Model")
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<Model>());
}
public virtual DbSet<MyEntity> MyEntities { get; set; }
}
public class MyEntity
{
private static readonly XmlSerializer Serializer = new XmlSerializer(typeof(Address));
public int Id { get; set; }
public string Name { get; set; }
[Column(TypeName = "xml")]
public string AddressData { get; protected set; }
[NotMapped]
public Address Address
{
get
{
using (var textWriter = new StringReader(AddressData))
{
return Serializer.Deserialize(textWriter) as Address;
}
}
set
{
using (var textWriter = new StringWriter())
{
using (var xmlWriter = XmlWriter.Create(textWriter))
{
Serializer.Serialize(xmlWriter, value);
}
AddressData = textWriter.ToString();
}
}
}
public override string ToString()
{
return string.Format("Id: {0}, Name: {1}, Address: {2}", Id, Name, Address);
}
}
public class Address
{
public string StreetLine1 { get; set; }
public string City { get; set; }
public string PostCode { get; set; }
public string Country { get; set; }
public override string ToString()
{
return string.Format("StreetLine1: {0}, City: {1}, PostCode: {2}, Country: {3}", StreetLine1, City, PostCode, Country);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="6.1.1" targetFramework="net45" />
</packages>
@RhysC
Copy link
Author

RhysC commented Jun 30, 2015

Consider a base class also

public abstract class MyEntityBase<T> where T : class
    {

        public int Id { get; set; }
        public string Name { get; set; }
        protected abstract XmlSerializer Serializer { get; }

        [Column(TypeName = "xml")]
        public string PayloadData { get; protected set; }

        [NotMapped]
        public T Payload
        {
            get
            {
                using (var textWriter = new StringReader(PayloadData))
                {
                    return Serializer.Deserialize(textWriter) as T;
                }
            }
            set
            {
                using (var textWriter = new StringWriter())
                {
                    using (var xmlWriter = XmlWriter.Create(textWriter))
                    {
                        Serializer.Serialize(xmlWriter, value);
                    }
                    PayloadData = textWriter.ToString();
                }
            }
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment