Ophiucus
Ophiucus

Reputation: 115

Generic query with Entity Framework ORM

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;
        }
    }

Upvotes: 0

Views: 747

Answers (1)

Felipe Oriani
Felipe Oriani

Reputation: 38638

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");

Upvotes: 3

Related Questions