Code-First应用程序中的XML列

我正在尝试在Code First中创建XML列。 我很清楚Entity Framework不完全支持XML列,并且它将它们作为字符串读取。 没关系。 不过,我仍然希望列类型是XML。 这是我的class级:

class Content { public int ContentId { get; set; } [Column(TypeName="xml")] public string XmlString { get; set; } [NotMapped] public XElement Xml { get { ... } set { ... } } } 

问题是,Code First Migrations完全忽略Column属性并将字段创建为nvarchar(max) 。 我尝试使用[DataType("xml")] ,但这也没有用。

这是迁移错误吗?

你有没有尝试过:

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

我实现了属性所需的东西,并用属性修饰了我的模型类xml字段。

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

得到了这两篇文章的帮助:

https://entityframework.codeplex.com/wikipage?title=Code%20First%20Annotations

https://andy.mehalick.com/2014/02/06/ef6-adding-a-created-datetime-column-automatically-with-code-first-migrations/

定义属性

 [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class XmlType : Attribute { } 

在Context中注册属性

在“OnModelCreating”的上下文中

 modelBuilder.Conventions.Add(new AttributeToColumnAnnotationConvention("XmlType", (p, attributes) => "xml")); 

自定义Sql生成器

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

注册自定义Sql生成器

在“迁移配置”构造函数中,注册自定义SQL生成器。

  SetSqlGenerator("System.Data.SqlClient", new CustomSqlGenerator()); 

但是如果XmlContent为null呢?

也许 :

  public XElement XmlValueWrapper { get { return XmlContent != null ? XElement.Parse(XmlContent) : null; } set { XmlContent = value.ToString(); } }