我认为Dapper在v1.50.5(或更早版本)已经有supportsXML数据类型,它可以将XML数据类型转换为XmlDocument、XDocument或XElement。
它确实在我的代码中将XML 数据类型转换为XElement。
2021 年 3 月 5 日的示例代码
返回 XML 类型数据的存储过程:
CREATE PROCEDURE spGetCarInformation
AS
DECLARE @Cfg XML
SET @Cfg = '<Configuration>
<A>111</A>
<B>222</B>
</Configuration>'
SELECT 1 AS Id, 'Test' AS Name, @Cfg AS [Configuration]
代码示例:
/* Program.cs */
using System;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Data.SqlClient;
using Dapper;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
/* query XML data from database */
using var connection = new SqlConnection("Data Source=; Initial Catalog=; User ID=; Password=");
Car car = connection.Query<Car>("EXEC spGetCarInformation").First();
Console.WriteLine(car.Name);
Console.WriteLine(car.Configuration.Element("A").Value);
Console.WriteLine(car.Configuration.Element("B").Value);
/* Insert XML data into database */
car = new Car
{
Id = 2,
Name = "New Car",
Configuration = new XElement
(
"Configuration",
new XElement("A", "333"),
new XElement("B", "444")
)
};
string cmdText = @"CREATE TABLE #Car
(
Id INT,
Name NVARCHAR(128),
Configuration XML
)
INSERT INTO #Car
VALUES
(@Id, @Name, @Configuration)
SELECT * FROM #Car
DROP TABLE #Car";
Car result = connection.Query<Car>(cmdText, car).First();
Console.WriteLine(result.Name);
Console.WriteLine(result.Configuration.Element("A").Value);
Console.WriteLine(result.Configuration.Element("B").Value);
}
}
class Car
{
public int Id { get; set; }
public string Name { get; set; }
public XElement Configuration { get; set; }
}
}
输出:
项目中添加的 Nuget 包:
<PackageReference Include="Dapper" Version="2.0.78" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="2.1.2" />
我在 .NET 5 上测试了代码,但应该也可以在 .Net Framework 4.7.2+ 和 System.Data.SqlClient 上运行。