JB06
JB06

Reputation: 1931

Generic method to return common field from different tables

I have around 15 tables that I am working with, and I am working on creating audit reports for these tables. All of these tables have a UserId column that gets updated with the last user's Id that made changes. I would like to create a repository method that would allow me to pass in what table entity to use for the method and then just return a list of the UserIds to use on the audit page, instead of allowing the user to type whatever they want in the UserId search field for the audit, I want to supply a dropdown with only the userIds that are in the table that I pass to the method.

I was thinking of something like this:

var ids = _repo.GetUserIds(//table entity here, unsure how to declare in signature);

Upvotes: 0

Views: 596

Answers (1)

JotaBe
JotaBe

Reputation: 39014

You need to make a generic method, with a type parameter that represents your type entity and access the corresponding DbSet<T> to get the data from that collection.

public int GetUserId<TEntity>()
{
   int userId;
   using (var cts = new MyDbContext())
   {
      userId = ctx.DbSet<TEntity>.FirstOrDefault().Select(e => e.UserId);
   }
   return userId;
}

To be able to include the projection lambda e => e.UserId you need to make all your classes implement an interface like this:

public interface IUserId
{
  public int UserId { get; set; }
}

And your generic class must have the corresponding type constraint:

public RepoClass<T>
   where T:IUserId
{
    // Define the generic method here
}

Upvotes: 1

Related Questions