Mehdi Sh.
Mehdi Sh.

Reputation: 29

c# Generic Query Builder

I would like to know if there is a better way to write this code.The main target is to let 'Select method' know which colum of our object we going to use in our query. I would like to have something like second code:

internal class Employee
{       
    public int ID { get; set; }
    public string Name { get; set; }
    public string Sex { get; set; }
    public int Age { get; set; }
}

public interface IRepository<T> where T : class
{
    void Select(string[] table);
}
public class Repository<T> : IRepository<T> where T : class
{
    public void Select(string[] table)
    {
        // Build Query
    }
}

public partial class Main
{

    public Main()
    {

        Repository<Employee> empRepository = new Repository<Employee>();

        Employee myemp = new Employee();
    
        string[] selectedColums = {nameof(myemp.ID), nameof((myemp.Sex) };
        empRepository.Select(selectedColums);
    }
}

Now in Main class i will do something like this:

public Main()
{

    Repository<Employee> empRepository = new Repository<Employee>();

    empRepository.Select(string[] selectedColums = {=>.Sex , =>.Name });
}

We Have already our Object so why we should have a new declaration of type Employee!

Thanks a lot.

Upvotes: 1

Views: 437

Answers (1)

Zer0
Zer0

Reputation: 7354

Putting @xanatos suggestions into code, is this what you're looking for?

public Main()
{
    Repository<Employee> empRepository = new Repository<Employee>();
    string[] selectedColums = { nameof(Employee.ID), nameof(Employee.Sex) };
    empRepository.Select(selectedColums);
}

Added bonus, nameof gets evaluated at compile time. So it can help catch errors before execution:

nameof(Employee.PropertyThatDoesntExist)

The above won't even compile.

Upvotes: 1

Related Questions