More Generic LinqHelper Class
8/14/2007 11:05:25 AM
I've implemented a LinqHelper class as kind of a way to test out more Generic Data Access with Linq to Sql. It's been working out quite well but there is at least 1 major gotcha... multiple databases (DataContext).
After Andy recommended reading Rick Strahl's blog post "Linq to Sql and Dynamic Queries" I figured I should repost the code that I wrote for my LinqHelper. I just posted a couple of methods so you could see where I was going with this. Stay tuned to Rick's post. I'm wondering how this is going to play out.
The thought of creating a class for each database is unacceptable so the following code should do the trick (for now!).
public abstract class LinqHelper<TDatabase>
where TDatabase : DataContext, new()
{
public static List<T> ReturnAllRows<T>() where T: class
{
return new TDatabase().GetTable<T>().ToList<T>();
}
public static bool EntityExists<T>(Expression<Func<T, bool>> predicate)
where T : class
{
return new TDatabase().GetTable<T>().Where<T>(predicate).Count() > 0;
}
public static List<T> Filter<T>(Expression<Func<T, bool>> predicate)
where T: class
{
return new TDatabase().GetTable<T>().Where(predicate).ToList<T>();
}
public static void Insert<T>(T entity) where T : class
{
using (TDatabase database = new TDatabase())
{
database.GetTable<T>().Add(entity);
database.SubmitChanges();
}
}
public static void Delete<T>(Expression<Func<T, bool>> predicate)
where T : class
{
if (!EntityExists<T>(predicate))
using (TDatabase database = new TDatabase())
{
T t = (T) database.GetTable<T>().Where<T>(predicate).Single();
database.GetTable<T>().Remove(t);
database.SubmitChanges();
}
}
}
C#,
Code,
LINQ
