I have trouble using Dapper
when i want to map my object from database.
class Set
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public List<Guid> GeneratorsList { get; set; }
}
It contains a list so I've created separated table that holds it, like that
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
);
And from those tables I want to retrieve correct Set object with minimum code effort. I've tried to do join on them and strong type the result to Set
, but with no success.
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];");
I'm aware that I could simply retrieve Set
from table and then add the GeneratorsList
from separate query, but I'm looking for a better solution.
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();
}
Is there a solution that require only one query ?
Using the query you provided you may receive:
internal class GeneratorSet
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Guid GeneratorId { get; set; }
}
And use linq
GroupBy
to construct the Set
object(-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)});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.