mercredi 9 décembre 2020

How to use reflection to pass the table name dynamically

I've never use reflection and I need to query the database and pass the table name dynamically. All tables that I am querying have the same signature(the same columns). I tried to follow the example from Dynamically set the table name in LINQ query but I am stuck now. I tried to call the 'Example' method, but I cannot call it like that. Thank you in advance for the help. I am completely clueless with reflection, if there is a better way of achieving my goal please point me to the right direction.

public void Example(IQueryable<IFileTable> dataSource)
{
    var data = (from q in dataSource
            select new 
            {
                ID = q.Id,
                FileName = q.FileName
            }).ToList();

     Console.Write(data);
}

public static void GetData()
{
    Example(DataConnection.Context.Test1.AsQueryable());
}
  

public interface IFileTable
{
    int Id { get; set; }
    string FileName { get; set; }
}

public partial class Test1: IFileTable
{
    public int Id { get; set; }
    public string FileName { get; set; }
}

public partial class Test2: IFileTable
{
    public int Id { get; set; }
    public string FileName { get; set; }
}




Aucun commentaire:

Enregistrer un commentaire