advanced web statistics

LINQ, Lambda, and Generics: Insert and Delete

8/10/2007 6:35:26 PM

I think I'm addicted.  Aside from my first LINQ application ("Hello AccountTypeId") I haven't written one SQL-like query.  From that point on everything has been done with Generics, Lambda expressions (Expression<> trees), and starting today: Reflection.  In the past I tried very hard not to have any SQL or SQL-like syntax in code so why should I start now?  Maybe I'll come around.  Personally I think using Generics coupled with Expression<> trees and Reflection makes for much more elegant code but that is just me. :-)

I, like others I'm sure; am just waiting to see how LINQ is going to play into this whole Presentation / Business / DataAccess layer scheme.  I can't find it right now but I do have a great link (2) to post discussing developer speculations on what is to become of a 3-tier architecture.

Anyway, some more code that I've been working on.

public static void Insert<T>(T entity) where T : class
{
   using (OrcasDB database = new OrcasDB())
   {
      database.GetTable<T>().Add(entity);
      database.SubmitChanges();
   }
}

public static void Delete<T>(Expression<Func<T, bool>> predicate)
where T : class
{
   using (OrcasDB database = new OrcasDB())
   {

      T instance = (T) database.GetTable<T>().Where<T>(predicate).Single();
      database.GetTable<T>().Remove(instance);
      database.SubmitChanges();
   }
}

How to Use
// insert
Employee will = new Employee
{
   Username = "will.asrari",
   EmailAddress = "me@willasrari.com",
   CanCode = true
};

LinqHelper.Insert<Employee>(will); 

// delete
LinqHelper.Delete(emp => emp.EmployeeId.Equals(3));

Easy.  My Delete<T> method could probably be made more elegant but this code does work.

UPDATE
I found the links that I wanted to post.  Pretty lengthy, but some interesting reading.

Creating a DAL with Linq to Sql Part 1
Creating a DAL with Linq to Sql Part 2

LINQ, Orcas

kick it on DotNetKicks.com

Leave a Comment

   

  Enter the text to proceed!