Две таблицы выглядят следующим образом: Game является основной таблицей, а SpecialConfig — тем, к чему я присоединяюсь. У него есть связь 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; }
}
Код: Выделить всё
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().Include(game=>game.Specials).Where(game=>game.GameId==gameId);
//var game = scope.Database.Query().Include(game=>game.SpecialsId).Where(game=>game.GameId==gameId).FirstOrDefault();
// ORIGINAL line
//var game = scope.Database.Query().Where(game=>game.GameId==gameId).FirstOrDefault();
scope.Complete();
return game.FirstOrDefault();
} catch (Exception ex) {
Log.Error("Error fetching game from database "+ex);
return null;
}
}
}
Может быть, мне вообще не нужно включать и все должно работать автоматически благодаря аннотациям ForeignKey?
Подробнее здесь: https://stackoverflow.com/questions/784 ... two-tables