advanced web statistics

LINQ and Generic GetRecord Method

6/4/2008 11:57:30 PM

Lately I've been abstracting some LINQ functionality into a Generic Data Access Class so that it can be reused across multiple projects without having to write out functionality over-and-over (i.e. creating a RetrieveProductsByProductId method, AddNewProduct, DeleteProduct, etc...).

CRUD'ing is a braindead process using LINQ & Generics.  I've found that Update is / can be a huge pain in the ass.  I currently have 2 versions of an update method (working on a 3rd) but just thought I'd kick-off the next couple of posts by posing the following question:

Question:  How well do you think the following would scale?

public T GetRecord<T>(int primaryKey) where T : class
{
   using (var database = new TData())
      return database.ExecuteQuery<T>(string.Format("SELECT * FROM {0} WHERE ID={1}", typeof(T).Name, primaryKey)).Single();

I found this little beauty during my travels to find examples of generic update methods.  This is obviously not an update method but definitely worthy of posting by me.  This seems a little too specific to the database implemented so it begs the question of why one would even try to make it generic.

Here's how I (and Dwight) would implement:

public static T GetRecord<T>(Expression<Func<T, bool>> predicate)
{
   if (predicate == null)
      throw new ArgumentNullException("predicate", "lulz");

   return new TData().GetTable<T>().Where(predicate).SingleOrDefault();
}

Not Shakespeare but it sure is a lot more practical than the previous example IMHO.

var foo = DataAccess<FooDB>.GetRecord<Foo>(f => f.Name == "Stihl 066");

Easy.  I'll be prepping some more entries related to Generic updating of SQL data soon.  I could really use some feedback from some more seasoned LINQ'ers.

C#, LINQ

kick it on DotNetKicks.com

Leave a Comment

   

  Enter the text to proceed!