I am using the NPoco framework (and Umbraco) and fetch a lot of data from single tables with it. Now, I want to join to tables together, but it seems like this is not working at all.
The two tables look like this with Game being the main table and SpecialConfig being something I join into it. It has a ForeignKeyRelationship
using NPoco;
using Umbraco.Cms.Infrastructure.Persistence.DatabaseAnnotations;
namespace Models.Dto;
[TableName("Game")]
[PrimaryKey("GameId", AutoIncrement = true)]
public class GameWithSpecialDto {
[Column("GameId")]
public int GameId { get; init; }
[Column("IsFinished")]
public bool IsFinished { get; init; }
// a couple of another elements
[Column("SpecialsId")]
[ForeignKey(typeof(SpecialConfigDto), Name = "FK__Game__SpecialsId__0E04126B")]
public required SpecialConfigDto SpecialsId { get; init; }
}
[TableName("SpecialConfig")]
[PrimaryKey("SpecialsId", AutoIncrement = true)]
public class SpecialConfigDto {
[Column("SpecialsId")]
public int SpecialsId { get; init; }
[Column("SpecialsName")]
public string? SpecialsName { get; init; }
}
The code for it is the following:
using Models.Dto;
using Serilog;
using Umbraco.Cms.Infrastructure.Scoping;
namespace Core.Repositories;
public class GameRepository {
private readonly IScopeProvider _scopeProvider;
public GameRepository(IScopeProvider scopeProvider) {
_scopeProvider = scopeProvider;
}
public GameWithSpecialDto? GetGame(int gameId) {
try {
using var scope = _scopeProvider.CreateScope();
var game = scope.Database.Query<GameWithSpecialDto>().Include<SpecialConfigDto>(game=>game.Specials).Where(game=>game.GameId==gameId);
//var game = scope.Database.Query<GameDto>().Include(game=>game.SpecialsId).Where(game=>game.GameId==gameId).FirstOrDefault();
// ORIGINAL line
//var game = scope.Database.Query<GameDto>().Where(game=>game.GameId==gameId).FirstOrDefault();
scope.Complete();
return game.FirstOrDefault();
} catch (Exception ex) {
Log.Error("Error fetching game from database "+ex);
return null;
}
}
}
The original line is without any joins (GameDTO is the same but without the foreign key), but now I want to join this in. After a bit of research, it concluded that I should use the Include command, but I get various error messages about wrong casting of elements there.
Maybe I do not need include at all and everything should work automagic due to the ForeignKey annotations?