Search code examples
c#xmlef-code-firstentity-framework-migrations

XML columns in a Code-First application


I'm trying to create an XML column in Code First. I'm well aware Entity Framework doesn't fully support XML columns, and that it reads them as a string. That's fine. I would still like the column type to be XML, though. Here's my class:

class Content
{
    public int ContentId { get; set; }

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

    [NotMapped]
    public XElement Xml { get { ... } set { ... } }
 }

Problem is, that Code First Migrations completely ignores the Column attribute and creates the field as an nvarchar(max) . I tried using [DataType("xml")], but that, too, didn't work.

Is this a migration bug?


Solution

  • Have you tried:

    public String XmlContent { get; set; }
    
    public XElement XmlValueWrapper
    {
        get { return XElement.Parse(XmlContent); }
        set { XmlContent = value.ToString(); }
    }
    
    public partial class XmlEntityMap : EntityTypeConfiguration<XmlEntity>
    {
        public XmlEntityMap()
        {
            // ...
            this.Property(c => c.XmlContent).HasColumnType("xml");
    
            this.Ignore(c => c.XmlValueWrapper);
        }
    }