Share via

Sql, C#: Get SQL XML AUTO to C# model

JDias 166 Reputation points
2022-01-17T16:16:22.847+00:00

I created an application that saves the state of a table (t) in XML everytime the user presses a button.

Conceptually, I do this with:

INSERT INTO Log (xml) VALUES ((SELECT * FROM t FOR XML AUTO));

The specs of the tables are similar to:

CREATE TABLE Log (xml XML NULL);

and:

CREATE TABLE t (i INTEGER, s NVARCHAR(MAX), d DATETIME);

The generated XML is like:

<t i="449" s="a string 1" d="2021-10-08T00:00:00" />
<t i="450" s="a string 2" d="2021-10-08T00:00:00" />
<t i="451" s="a string 3" d="2021-10-06T00:00:00" />

with no root.

Now, I have read the XML from the database back to C# as a string.

How may I convert this XML to my model:

public class tModel {
public long i;
public string s;
public DateTime d;
}

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,606 Reputation points Volunteer Moderator
    2022-01-17T20:51:18.637+00:00

    If by chance this is EF Core than look at IDbCommandInterceptor and use XElement.Parse(... to extract xml to your model.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.