Dapper从JOIN查询接收List作为对象参数

时间:2017-09-06 12:45:26

标签: c# sql-server dapper

当我想从数据库映射我的对象时,我无法使用Dapper

class Set
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public List<Guid> GeneratorsList { get; set; }
}

它包含一个列表,所以我创建了包含它的分隔表,就像那个

CREATE TABLE [dbo].[Sets] (
    [Id]          UNIQUEIDENTIFIER NOT NULL,
    [Name]        VARCHAR (60)     NOT NULL,
    [Description] VARCHAR (60)     NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

CREATE TABLE [dbo].[Set_Generator] (
    [SetId]       UNIQUEIDENTIFIER NOT NULL,
    [GeneratorId] UNIQUEIDENTIFIER NOT NULL,
    PRIMARY KEY CLUSTERED ([SetId] ASC, [GeneratorId] ASC),
    FOREIGN KEY ([SetId]) REFERENCES [dbo].[Sets] ([Id]) ON DELETE CASCADE
);

从这些表中我想用最少的代码工作来检索正确的Set对象。我已经尝试加入他们并强选将结果输入Set,但没有成功。

var result = conn.Query<Set>(@"SELECT [S].[Id], [S].[Name], [S].[Description], [SG].[GeneratorId] AS [GeneratorsList] FROM [Sets] AS [S] INNER JOIN [Set_Generator] AS [SG] ON [S].[Id] = [SG].[SetId];");

我知道我只能从表中检索Set,然后从单独的查询中添加GeneratorsList,但我正在寻找更好的解决方案。

var sets = conn.Query<Set>(@"SELECT * FROM [Sets];");
foreach(var set in sets)
{
    var generators = conn.Query<Guid>(@"SELECT [GeneratorId] FROM [Set_Generator] WHERE [SetId]=@SetId", new { SetId = set.Id });
    set.GeneratorsList = generators.ToList();
}

是否有只需要一个查询的解决方案?

1 个答案:

答案 0 :(得分:1)

使用您提供的查询,您可能会收到:

internal class GeneratorSet
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public Guid GeneratorId { get; set; }
}

使用linq GroupBy构建Set对象(-s):

var generatorSets = conn.Query<GeneratorSet>(@"SELECT [S].[Id], [S].[Name], [S].[Description], [SG].[GeneratorId] AS [GeneratorsList] FROM [Sets] AS [S] INNER JOIN [Set_Generator] AS [SG] ON [S].[Id] = [SG].[SetId];");;

var res = generatorSets.GroupBy(gen => gen.Id, p => p, (key, g) => new Set()
      { Id = key, Generators = g.Select(g => g.GeneratorId)});