0

I have 3 classes, Client, Payee and LookupFile, and I'm planning to use a generic repository pattern to work with the database.

The LookupFile and Payee always have a Client associated with them.

When querying for a LookupFile or Payee, I want to include the related Client so I included the Client object in the base entity. Now this is creating a self referencing key in the Client table when I run migrations.

How do I go about not having a self referencing Client table and also be able to include the related Client record when querying the LookupFile and Payee?

public class BaseEntity
{
    public int Id { get; set; }
    public Client Client { get; set; } //Added client object so it be used in include
}

public class Payee : BaseEntity
{
    public int ClientId { get; set; }
    public string PayeeName { get; set; }
}

public class LookupFile : BaseEntity
{
    public int ClientId { get; set; }
    public string FileName { get; set; }
}

public class Client : BaseEntity
{
    public string ClientName { get; set; }
}

// Then my GenericRepository is defined as below:
public class DataRepository<T> : IBaseRepository<T> where T : BaseEntity
{
    private readonly ApplicationDbContext _context;

    public DataRepository(ApplicationDbContext context)
    {
        _context = context;
    }
    
    public async Task<IEnumerable<T>> GetAll()
    {
        return await _context.Set<T>()
                             .AsNoTracking()
                             .Include(c => c.Client)
                             .ToListAsync();
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ICICI81
  • 101
  • 1
  • 9
  • 4
    The simple answer, don't use the generic Repository (anti-)pattern. The more complete answer, see: https://stackoverflow.com/questions/70760405/modifying-existing-generic-repository-pattern-to-add-select/70762122#70762122 – Steve Py Feb 05 '22 at 02:43
  • Thank you. I stopped inheriting Base Entity for the Client and made a separate Client specific repository. – ICICI81 Feb 05 '22 at 03:28
  • 2
    Even better, don't use repositories, `DbContext` already provides abstracted data access ;) – Fabio Feb 05 '22 at 11:29

0 Answers0