I don't even want to know how many times I have written something like this:
var p = db.Products.FirstOrDefault(x => x.Id == someId);
Then 4 lines down, do it again almost exactly the same, over and over, at least once for each table.
Well... no more!
Now that I am able to
get the Primary Key of any Linq-to-SQL talbe, it is trival to be able to write a universal get statement so I can simply do this when I want to grab an object by it's Primary Key:
Product p = db.Get<Product>(someId);
What if I want to get an item that has a
Guid as a primary key?
Same thing, it doesn't matter:
Guid gId =
new Guid("4fcc0b82-b137-4e4b-935e-872ed662ba53");
Gizmo g = db.Get<Gizmo>(gId);
If you you give the wrong Type of Key, it will tell you in a nice
ArgumentException:
Gizmo g = db.Get<Gizmo>(5);
Error:
Primary Key of Table and primaryKey argument are not of the same Type; Primary Key of Table is of Type: System.Guid, primaryKey argument supplied is of Type: System.Int32
Here is the code without any error handling:
public static T Get<T>(this DataContext dataContext,
object primaryKey)
where T : class, INotifyPropertyChanged
{
return dataContext.GetTable(typeof(T))
.Cast<T>()
.Where(GetPrimaryKey<T>()
.Name + ".Equals(@0)", primaryKey)
.FirstOrDefault();
}
The full code is available in my
Utilities class on CodePlex.
This requires
System.Linq.Dynamic.