You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过ID关联表数据并使用.NET Core API返回关联详情

查询Country及关联State的实现方案

是否需要使用Join?

  • 若使用Entity Framework Core(EF Core):无需手动编写JOIN语句,通过导航属性即可自动关联查询关联数据,这也是.NET Core中推荐的方式,对新手更友好。
  • 若使用ADO.NET(直接写SQL):需要手动编写JOIN关联两张表,再自行处理查询结果组装成目标结构。

EF Core 实现方式(推荐)

1. 定义实体类(对应数据库表)

// Country实体类
public class Country
{
    public int Id { get; set; }
    public string Name { get; set; }
    // 导航属性:关联当前Country下的所有State
    public ICollection<State> States { get; set; } = new List<State>();
}

// State实体类
public class State
{
    public int Id { get; set; }
    public string StateName { get; set; }
    public int CountryId { get; set; }
    // 可选:反向导航属性,关联所属Country
    public Country Country { get; set; }
}

2. 配置DbContext(数据库上下文)

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

    // 声明数据库表对应的DbSet
    public DbSet<Country> Countries { get; set; }
    public DbSet<State> States { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // 配置State与Country的外键关联关系
        modelBuilder.Entity<State>()
            .HasOne(s => s.Country)
            .WithMany(c => c.States)
            .HasForeignKey(s => s.CountryId);
    }
}

3. DAL层查询方法

public class CountryRepository
{
    private readonly AppDbContext _dbContext;

    // 通过构造函数注入DbContext
    public CountryRepository(AppDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    // 根据Country Id查询详情及关联的State列表
    public async Task<Country> GetCountryWithStatesAsync(int countryId)
    {
        // 使用Include方法加载关联的States集合
        return await _dbContext.Countries
            .Include(country => country.States)
            .FirstOrDefaultAsync(country => country.Id == countryId);
    }
}

调用该方法后,返回的Country对象会自动包含对应的States数组,直接返回即可得到你需要的格式。


ADO.NET 实现方式(手动写SQL)

如果不使用EF Core,直接通过ADO.NET操作数据库,需要手动处理JOIN和结果组装:

public class CountryRepository
{
    private readonly string _connectionString;

    public CountryRepository(string connectionString)
    {
        _connectionString = connectionString;
    }

    public Country GetCountryWithStates(int countryId)
    {
        Country targetCountry = null;
        using (var connection = new SqlConnection(_connectionString))
        {
            connection.Open();
            // 编写JOIN查询SQL
            var querySql = @"
                SELECT c.Id AS CountryId, c.Name, s.Id AS StateId, s.StateName, s.CountryId
                FROM Country c
                LEFT JOIN State s ON c.Id = s.CountryId
                WHERE c.Id = @CountryId";

            using (var command = new SqlCommand(querySql, connection))
            {
                command.Parameters.AddWithValue("@CountryId", countryId);
                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        // 首次读取时初始化Country对象
                        if (targetCountry == null)
                        {
                            targetCountry = new Country
                            {
                                Id = reader.GetInt32(reader.GetOrdinal("CountryId")),
                                Name = reader.GetString(reader.GetOrdinal("Name")),
                                States = new List<State>()
                            };
                        }

                        // 读取并添加关联的State(若存在)
                        if (!reader.IsDBNull(reader.GetOrdinal("StateId")))
                        {
                            var state = new State
                            {
                                Id = reader.GetInt32(reader.GetOrdinal("StateId")),
                                StateName = reader.GetString(reader.GetOrdinal("StateName")),
                                CountryId = reader.GetInt32(reader.GetOrdinal("CountryId"))
                            };
                            targetCountry.States.Add(state);
                        }
                    }
                }
            }
        }
        return targetCountry;
    }
}

内容的提问来源于stack exchange,提问作者Saran S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 13:53:10