XML data type in EF 4.1 Code First
Asked Answered
T

3

12

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 string type:

public class XmlEntity
{
   public int Id { get; set; }

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

The table is correctly generated in the datebase by this definition. New XmlEntity objects are also can be created.

But then I try to get some entity from the database:

var entity = db.XmlEntities.Where(e => e.Id == 1).FirstOrDefault();

An error occurs:

One or more validation errors were detected during model generation System.Data.Edm.EdmEntityType: EntityType 'XElement' has no key defined. Define the key for this EntityType.

Tevis answered 25/8, 2011 at 12:52 Comment(0)
T
18

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.

Tevis answered 25/8, 2011 at 13:5 Comment(1)
@Tevis , great question and answer, but wouldn't the question make more sense if you included the XElement property in it -- per the MSDN articles? Currently there is no XElement property. So it's unclear that the only change is [NotMapped] attribute.Mohammadmohammed
B
8

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(); }
}
Binocular answered 11/5, 2012 at 13:37 Comment(0)
N
3

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>()

Neslund answered 12/5, 2012 at 16:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.