如何将存储过程的 XML 输出转换为 Asp Net Core 中的 C# 对象

How to Convert XML output from Stored Procedure to C# object in Asp Net Core

SET ANSI_NULLS ON; GO SET QUOTED_IDENTIFIER ON; GO ALTER PROC
[dbo].[getStateWiseCompanyDetails] AS
BEGIN
With Data
     AS (SELECT Companies.RegionId,
                Companies.Code,
                Companies.CompanyName,
                Users.FirstName,
                Companies.OfficePhone
         FROM Companies
              INNER JOIN Users ON Companies.DirectorId = Users.Id)
     SELECT States.Id AS RegionId,
            States.StateName,
            States.IsRegion AS Status,
            Users.FirstName + ' ' + Users.LastName AS RegionDirector,
            Users.PhoneNumber,
     (
         SELECT *
         FROM Data
         WHERE data.RegionId = States.Id FOR XML PATH('CompanyList'), ROOT('StateWiseCompany'), TYPE
     ) AS CompanyList
     FROM States
          INNER JOIN Users ON States.RegionDirector = Users.Id;
END;

存储过程的实际输出

将包含这些信息的最后一列

我想在我的 dot net Core Web 应用程序中调用这个存储过程。

根据您的描述,如果您已经使用EF core创建数据库,可以通过_dbContext.<yourdbsetclass>.FromSqlRaw方法接收存储过程数据。我建议您可以尝试为 EF 创建自定义 ValueConverter 来满足您的要求。

当您使用 EF 核心从 sqldatbase 获取数据时,valueconvert 可以将字符串转换为对象,并在您要将数据插入数据库时​​将对象转换为字符串。

更多详情,您可以参考以下代码:

首先,您应该创建 StateWiseCompany class

[XmlRoot(ElementName = "CompanyList")]
public class CompanyList
{
    [XmlElement(ElementName = "RegionId")]
    public string RegionId { get; set; }
    [XmlElement(ElementName = "Code")]
    public string Code { get; set; }
    [XmlElement(ElementName = "CompanyName")]
    public string CompanyName { get; set; }
    [XmlElement(ElementName = "FirstName")]
    public string FirstName { get; set; }
    [XmlElement(ElementName = "OfficePhone")]
    public string OfficePhone { get; set; }
}

[XmlRoot(ElementName = "StateWiseCompany")]
public class StateWiseCompany
{
    [XmlElement(ElementName = "CompanyList")]
    public List<CompanyList> CompanyList { get; set; }
}

其次,您应该创建转换器 class:

public class ObjectToDbStringEquivalentConvertor<T> : ValueConverter<T, string>
{
    public ObjectToDbStringEquivalentConvertor(ConverterMappingHints mappingHints = null) : base(convertToProviderExpression, convertFromProviderExpression, mappingHints)
    { }

    private static Expression<Func<T, string>> convertToProviderExpression = x => ToDbString(x);
    private static Expression<Func<string, T>> convertFromProviderExpression = x => ToObject<T>(x);

    public static string ToDbString<T>(T obj)
    {

        using (var stringwriter = new System.IO.StringWriter())
        {
            var serializer = new XmlSerializer(typeof(T));
            serializer.Serialize(stringwriter, obj);
            return stringwriter.ToString();
        }

     }

    public static T ToObject<T>(string stringValue)
    {
        if (stringValue != string.Empty)
        {
            using (var stringReader = new System.IO.StringReader(stringValue))
            {
                var serializer = new XmlSerializer(typeof(T));
                var re = serializer.Deserialize(stringReader);
                return (T)re;
            }
        }
        else
        {
            throw new Exception();
        }
  
    }



}

第三,您应该将 dbcontext 模型的 属性 类型从字符串修改为对象。

public class Organization
{
    [Key]
    public int OrgID { get; set; }
    public StateWiseCompany OrgName { get; set; }
}

第四,我建议您修改 dbcontext 以重写 OnModelCreating 方法,如下所示:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Organization>(
            entity => {
                entity.HasKey(e => e.OrgID);
                entity.Property(e => e.OrgName).HasConversion(new ObjectToDbStringEquivalentConvertor<StateWiseCompany>());
                }
           
            ) ;

    }

终于可以使用EF core dbcontext调用SP了:

        var re = _dbContext.Organizations.FromSqlRaw("EXEC [dbo].[getStateWiseCompanyDetails]").ToList();

结果:

数据库:

查询结果: