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 ?
QueryMultiplestackoverflow.com/questions/6751052/…