Search code examples
c#insight.database

Insight.Database Auto Interface & Mapping Many-to-Many


Assuming I have the following tables:

CREATE TABLE Game
(
  GameId INT,
  Name VARCHAR(50)
)

CREATE TABLE UserGameJoin
(
  GameId INT,
  UserId INT
)

CREATE TABLE User
(
  UserId INT,
  Username VARCHAR(50)
)

And the following classes:

public class Game
{
  public int GameId {get;set;}
  public string Name {get;set;}
  public List<User> Users {get;set;}
}

public class User
{
  public int UserId {get;set;}
  public string Username {get;set;}
}

How would I go about mapping results from this stored procedure

CREATE PROC GetGamesAndUsers
AS
SELECT *
FROM Game

SELECT GameId, u.*
FROM Game g
INNER JOIN UserGameJoin j ON j.GameId = g.GameId
INNER JOIN User u ON u.UserId = j.UserId

to an auto interface implementation?

public interface IGameLibrary
{
  List<Game> GetGamesAndUsers();
}

I've played around with the Recordset attribute by adding

[Recordset(1, typeof(User), Id = "GameId", IsChild = true)]

But when calling connection.As() an InvalidOperationException is thrown: "Sequence contains no matching elements."


Solution

  • You had it right, but it looks like there's a bug when the interface returns a List instead of an IList and you specify the Id field.

    If you return an IList instead, the call should work.

    public interface IGameLibrary 
    {
      [Recordset(1, typeof(User), Id = "GameId", IsChild = true)]
      IList<Game> GetGamesAndUsers();
    }
    

    I've opened this as issue #136 and it will be fixed in v4.2.7.

    https://github.com/jonwagner/Insight.Database/issues/136