How to select database items recursively in C# using EF Core?

Viewed 58

I have the following objects:

public class AccountDTO
{
    public long Id { get; set; }

    [MaxLength(30), MinLength(6)]
    [Required]
    public string Username { get; set; }

    [MaxLength(50), MinLength(6)]
    public string Password { get; set; }

    [MaxLength(50)]
    public string? SecondaryPassword { get; set; }

    public SystemInformationDTO? SystemInformation { get; set; }
}

public class SystemInformationDTO
{
    public long Id { get; set; }

    [MaxLength(50)]
    public string? Os { get; set; }

    [MaxLength(50)]
    public string? Cpu { get; set; }

    [MaxLength(50)]
    public string? Gpu { get; set; }
}

And the following context class:

public class AccountContext : DbContext
{
    public DbSet<AccountDTO>? Account { get; set; }
    public DbSet<SystemInformationDTO>? SystemInformation { get; set; }

    public AccountContext()
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        options.UseSqlServer("myConnectionString");
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<AccountDTO>()
            .ToTable("Account", "Account");

        builder.Entity<AccountDTO>()
            .HasOne(x => x.SystemInformation);

        builder.Entity<SystemInformationDTO>()
            .ToTable("SystemInformation", "Account");
    }
}

With this, my database is generated as I wanted. I also populated properly.

Now, I have this repository using my context:

public class AccountQueriesRepository : IAccountQueriesRepository
{
    private readonly AccountContext _context;

    public AccountQueriesRepository(AccountContext context)
    {
        _context = context;
    }

    public AccountDTO? GetAccountByUsername(string username)
    {
        return _context?.Account?
            .Include(x => x.SystemInformation)
            .FirstOrDefault(x => x.Username == username);
    }

    public AccountDTO? GetAccountById(long id)
    {
        return _context?.Account?
            .Include(x => x.SystemInformation)
            .FirstOrDefault(x => x.Id == id);
    }
}

But when I call the GetAccount (by id or by username, whatever) it does not retrieve the SystemInformation.

How can I do it without creating separated "selects" in my context?

Thanks!

Edit:

Database screenshot

0 Answers
Related