Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML data type in EF 4.1 Code First

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.

like image 654
alexey Avatar asked Aug 25 '11 12:08

alexey


People also ask

What is XML data type?

The xml data type is a built-in data type in SQL Server and is somewhat similar to other built-in types such as int and varchar. As with other built-in types, you can use the xml data type as a column type when you create a table as a variable type, a parameter type, a function-return type, or in CAST and CONVERT.

What is DbContext in Entity Framework?

A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.


1 Answers

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.

like image 53
alexey Avatar answered Sep 16 '22 15:09

alexey