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?
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);
}
}
I achieved what is needed with an attribute and I decorated my model class xml field with the attribute.
[XmlType]
public string XmlString { get; set; }
[NotMapped]
public XElement Xml
{
get { return !string.IsNullOrWhiteSpace(XmlString) ? XElement.Parse(XmlString) : null; }
set {
XmlString = value == null ? null : value.ToString(SaveOptions.DisableFormatting);
}
}
Got the help of these 2 articles:
https://entityframework.codeplex.com/wikipage?title=Code%20First%20Annotations
Solution
Define Attribute
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class XmlType : Attribute
{
}
Register Attribute in Context
In the "OnModelCreating" of the context
modelBuilder.Conventions.Add(new AttributeToColumnAnnotationConvention<XmlType, string>("XmlType", (p, attributes) => "xml"));
Custom Sql Generator
public class CustomSqlGenerator : SqlServerMigrationSqlGenerator
{
protected override void Generate(ColumnModel column, IndentedTextWriter writer)
{
SetColumnDataType(column);
base.Generate(column, writer);
}
private static void SetColumnDataType(ColumnModel column)
{
// xml type
if (column.Annotations.ContainsKey("XmlType"))
{
column.StoreType = "xml";
}
}
}
Register Custom Sql Generator
In the Migration Configuration constructor, register the custom SQL generator.
SetSqlGenerator("System.Data.SqlClient", new CustomSqlGenerator());
But what if XmlContent is null ??
Maybe :
public XElement XmlValueWrapper
{
get { return XmlContent != null ? XElement.Parse(XmlContent) : null; }
set { XmlContent = value.ToString(); }
}
来源:https://stackoverflow.com/questions/12631290/xml-columns-in-a-code-first-application