使用 C# 在 ASP.NET Core 中进行对象映射

问题描述 投票:0回答:1

我是 ASP.NET Core 新手,请帮助我。我正在尝试将类对象与 SQL Server 数据库表映射;请帮助我获得这样的愿望输出:

[
    {
        "ID": 1,
        "Line1": "myaddress",
        "Line2": "address2",
        "City": "mycity",
        "State": {
                     "StateID": 1,
                     "StateName": "mystate"
                 },
        "StateID": 1,
        "ZipCode":"545588"
    }
]

我的课程是:

public class Address
{
    public int Id { get; set; }
    public string Line1 { get; set; }
    public string Line2 { get; set; }
    public string City { get; set; }
    public State State { get; set; }
    public string ZipCode { get; set; }
}

public class State
{
    public int StateId { get; set; }
    public string StateName { get; set; }
}

数据库表是:

CREATE TABLE [dbo].[address]
(
    [id] [bigint] IDENTITY(1,1) NOT NULL,
    [line1] [varchar](50) NULL,
    [line2] [varchar](50) NULL,
    [city] [varchar](50) NULL,
    [stateid] [int] NULL,
    [zipcode] [varchar](20) NULL,
)

CREATE TABLE [types].[state] 
(
    [stateid] [int] IDENTITY(1,1) NOT NULL,
    [statename] [text] NULL
)

从数据库读取数据的代码:

await using var conn_payoraddr = new SqlConnection(_connectionString.Value);
string query = "Select * from Address t1 left join types.State t2 on t1.stateid = t2.stateid where PayorId = @Id";

var result_addr = await conn_payoraddr.QueryAsync<PayorAddress>(query, new { Id = id });
c# asp.net-core .net-core asp.net-core-mvc
1个回答
0
投票

根据您的代码,似乎您正在使用dapper,通过使用dapper查询多个表并与嵌套对象映射,您需要在写入查询方法期间设置state属性。

更多详情,您可以参考下面的例子:

由于您的代码包含PayorAddress,但您只使用Address类,所以我直接查询并将数据映射到Address类:

        using var conn = new SqlConnection(connectionString);
        int id = 1;
        string query = @"
    SELECT t1.*, t2.*
    FROM Address t1
    LEFT JOIN type.State t2 ON t1.stateid = t2.stateid
    WHERE t1.Id = @Id";

        var result = (await conn.QueryAsync<Address, State, Address>(
            query,
            (Address, state) => {
                Address.State = state;
                return Address;
            },
            new { Id = id },
            splitOn: "stateid"
        )).FirstOrDefault();

班级:

public class Address
{
    public long Id { get; set; }
    public string Line1 { get; set; }
    public string Line2 { get; set; }
    public string City { get; set; }
    public int StateId { get; set; }
    public State State { get; set; }
    public string ZipCode { get; set; }
}
public class State
{
    public int StateId { get; set; }
    public string StateName { get; set; }
}

结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.