【问题标题】:Dapper query object with a child of IEnumerable具有 IEnumerable 子项的 Dapper 查询对象
【发布时间】:2018-02-27 15:51:55
【问题描述】:

我正在尝试查询所有国家/地区,并且在每个国家/地区对象中它会填满省份。

我有以下课程

public class Country
{
    public int Countryid { get; set; }
    public string CountryName { get; set; }

    public IEnumerable<Province> Provinces { get; set; }
}

public class Province
{
    public int ProvinceId { get; set; }
    public string ProvinceName { get; set; }
}

public IEnumerable<Country> GetCountries()
{
    var query = @"
          SELECT [Country].[CountryId], [Country].[Name] as CountryName, [Province].[ProvinceId], [Province].[Name] as ProvinceName
          FROM [Province]
            RIGHT OUTER JOIN [Country] ON [Province].[CountryId] = [Country].[CountryId]
          WHERE [Country].[CountryId] > 0";

    return _connection.Query<Country, Province, Country>(query, (country, province) =>
    {
        country.Provinces = country.Provinces.Concat(new List<Province> { province });
        return country;
    }, null);
}

我得到的错误如下:

System.ArgumentException: '使用多映射 API 时,如果您有除 Id 以外的键,请确保设置 splitOn 参数 参数名称:splitOn'

我一直在关注这个例子:

https://gist.github.com/Lobstrosity/1133111

从我的角度来看,除了我认为应该无关紧要的外连接之外,我看不出我所做的有什么不同,结果格式大致相同。

为什么我需要拆分,没有它可以工作吗?

【问题讨论】:

  • 在要点中,他使用Id是主键列,而您有CountryId和ProvinceId。将拆分设置为 ProvinceId,它应该可以正常工作
  • @Slicksim 我试过了,但是我得到的问题是我得到了 100 条记录,因为那是数据库中省份的总数。有 10 个国家和 100 个省,那么我如何只取回 10 行并让省成为各自国家的一部分?至于身份,我明白你的观点以及他的不同之处。

标签: c# asp.net asp.net-mvc asp.net-mvc-5 dapper


【解决方案1】:

IIRC,我做了这样的事情。

 var query = @"
          SELECT [Country].[CountryId], [Country].[Name] as CountryName, [Province].[ProvinceId], [Province].[Name] as ProvinceName
          FROM [Province]
            RIGHT OUTER JOIN [Country] ON [Province].[CountryId] = [Country].[CountryId]
          WHERE [Country].[CountryId] > 0";

    List<Country> countries = new List<Country>();      

    _connection.Query<Country, Province, Country>(query, (country, province) =>
    {           
        Country lastCountry = countries.FirstOrDefault(d => d.CountryId == country.Id);
        if(lastCountry == null)
        {
            countries.Add(country);
            lastCountry = country;

        }
        lastCountry.Provinces = lastCountry.Provinces.Concat(new List<Province> { province });
        return lastCountry;
    }, null);

    return countries;

我在 LinqPad 中输入了这个,所以你需要调试并检查它是否正确,我已经很久没有在愤怒中使用 Dapper

【讨论】:

  • 看,我认为这行不通,因为国家/地区超出了传入函数的范围。为什么你可以在那里实现?
  • 这取决于捕获的变量和闭包。您可以在这篇文章中了解更多信息:csharpindepth.com/Articles/Chapter5/Closures.aspx
猜你喜欢
  • 2022-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-16
  • 2016-07-04
相关资源
最近更新 更多