Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an (Sql Server) xml column with Entity Framework

Has anyone tried to use xml typed columns with Entity Framework ? The entity returns a string.

Will the next version of Entity Framework support XElement types when the table column is of type XML.

Regards.

like image 939
Alexandre Brisebois Avatar asked Apr 14 '09 16:04

Alexandre Brisebois


2 Answers

Entity Framework returns XML columns contents(typed or not) as strings so it can't create an entity from the xml documents content(it's nodes)... if you are still curious read this article, it gives a possible solution to your problem..i didn't tried it though(link text)

to answer Marc's last question..what i expect to see in the next version of EF is the possibility to map xml documents contents as entities, like it does with normal tables and the relationships between them.. or at least to make parts of the xml document as properties in entities..

like image 56
Sorin Antohi Avatar answered Oct 25 '22 01:10

Sorin Antohi


Here's what I'm doing now, I'm adding a method to a partial class matching my model that has a .Data property as a string.

Essentially you have call instance.UseData((data) => { ... });

From there within the lambda expression you can read/manipulate data and it saves back to the original field for the database... I'd love to just be able to create a property for this, that is bound to an event to update the related field.

I'm shoving more dynamic structure into the Data field as XML... this is more natural in VB.Net that C#.. if my project were in C# I might be inclined to favor JSON...

C#

public void UseData(Action<XElement> editor)
{
    var def = XElement.Parse("<Data></Data>");
    XElement data;
    try
    {
        if (String.IsNullOrWhiteSpace(this.Data))
        {
            data = def;
        }
        else
        {
            data = XElement.Parse(this.Data);
        }
    }
    catch (Exception ex)
    {
        data = def;
    }
    editor(data);
    this.Data = data.ToString();
}

VB.Net

Public Sub UseData(editor As Action(Of XElement))
    Dim def = <Data></Data>
    Dim data As XElement
    Try
        If String.IsNullOrWhiteSpace(Me.Data) Then
            data = def
        Else
            data = XElement.Parse(Me.Data)
        End If
    Catch ex As Exception
        data = def
    End Try
    editor(data)
    Me.Data = data.ToString()
End Sub
like image 20
Tracker1 Avatar answered Oct 25 '22 01:10

Tracker1