0

So currently i am writing a specific SQL function to get a specific row from a specific table.

However, I have dozens of tables, and noticed that I am writing these same 'get row' repository functions each time I make a new table.

Is it possible to write a generic function that works for every table, in this case to get a specific row?

Current (Example)

   public Purchase GetPurchase(long purchaseId)
    {
        using (var db = new DbContext(_connStringKey))
        {
            var result = (from p in db.Purchases
                          where p.PurchaseId.Equals(purchaseId)
                          select p).FirstOrDefault();
            return result;
        }
    }

Generic Example (To give you an idea)

  public Object GenericGet (string tableName, string rowName, long rowId)
    {
        using (var db = new DbContext(_connStringKey))
        {
            var result = (from p in db.tableName
                          where p.rowName.Equals(rowId)
                          select p).FirstOrDefault();
            return result;
        }
    }
5
  • 3
    Why would you do that? Commented Sep 20, 2017 at 17:38
  • You should probably look up Entity Framework or generating .tt templates in C# to get started. Commented Sep 20, 2017 at 17:50
  • Why do you have dozens of tables to hold purchases? Commented Sep 20, 2017 at 18:05
  • I have one table to hold purchases, but dozens of tables that require getting a specific row. Commented Sep 20, 2017 at 19:13
  • Edited the Question so it would be more clear. Commented Sep 20, 2017 at 19:21

1 Answer 1

3

You can do it using reflection but it is not a good approach. Instead of this, you could try something using the generics aspects of the language, and make sure what you want, for sample:

public T Get<T>(Expression<Func<T, bool>> filter)
    where T : class
{
   T result;
   using (var db = new DbContext(_connStringKey))
   {
      result = db.Set<T>().FirstOrDefault(filter);
   }
   return result;
}

Remember that the T must be a reference type, so, define a constraint for class

Then, you could try this:

var product = Get<Product>(p => p.Name == "Something");
var supplier = Get<Supplier>(p => p.Sector == "Manufacturing");
Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately when trying it I get an error with regards to the Db.Set<T>().FirstOrDefault(filter). The error is at the Db.Set. "The Type T must be a reference type."
Yes, It was missing the constraint, see my updates.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.