XML data type in EF 4.1 Code First

前端 未结 3 1558
陌清茗
陌清茗 2021-02-05 17:35

I would like to use SQL Server xml type as a column type for an entity class.

According to this thread it\'s possible to map such a column to st

相关标签:
3条回答
  • 2021-02-05 18:13

    Just to be complete. Here's all code needed, in one part.

    [Column(TypeName = "xml")]
    public String XmlContent { get; set; }
    
    [NotMapped]
    public XElement InitializedXmlContent
    {
        get { return XElement.Parse(XmlContent); }
        set { XmlContent = value.ToString(); }
    }
    
    0 讨论(0)
  • 2021-02-05 18:17

    The problem was with my wrapper property:

    [NotMapped]
    public XElement XmlValueWrapper
    {
        get { return XElement.Parse(XmlValue); }
        set { XmlValue = value.ToString(); }
    }
    

    I didn't specified NotMapped attribute.

    0 讨论(0)
  • 2021-02-05 18:28

    This's how you do that in Data Annotations, if you want to use Fluent API (and use a mapping class) then:

    public partial class XmlEntityMap : EntityTypeConfiguration<XmlEntity>
    {
        public FilterMap()
        {
            // ...
            this.Property(c => c.XmlContent).HasColumnType("xml");
    
            this.Ignore(c => c.XmlValueWrapper);
        }
    }
    

    If you use Fluent API by overriding OnModelCreating on DbContext then just change those "this" with modelBuilder.Entity<XmlEntity>()

    0 讨论(0)
提交回复
热议问题