I'm trying to write a generic Ling to SQL GetObjectById() method for getting a data object from the database based on a primary key id value, so that instead of having to write... MyDataContext dataContext = new MyDataContext(); Product myProduct = dataContext.Products.SingleOrDefault<Product>(p => p.Id == productId);
...I instead write... Product myProduct = Product.FromId(productId);
...which I think is much cleaner. Now I could simply write individual 'FromId' methods in each mapped data class, but where's the fun in that. So I tried to write a more generic one size fits all method for doing this and came up with the following...
public abstract class BaseTable<T>
{
public static T FromId(int id)
{
MyDatabaseDataContext dataContext = DatabaseContextHelper.GetDatabaseContext();
StringBuilder sql = new StringBuilder();
sql.Append("SELECT ");
MetaTable metaTable = dataContext.Mapping.MappingSource.GetModel(typeof(TopicDatabaseDataContext))
.GetMetaType(typeof(T)).Table;
foreach (MetaDataMember dm in metaTable.RowType.DataMembers)
{
if (dm.DbType != null)
{
sql.Append(dm.MappedName).Append(",");
}
}
sql.Remove(sql.Length - 1, 1);
sql.Append(" FROM ").Append(metaTable.TableName).Append(" WHERE Id = ").Append(id);
return dataContext.ExecuteQuery<T>(sql.ToString()).FirstOrDefault<T>();
}
}
I need to ensure all the mapped data classes extend BaseTable<T> but this does seem to work, however, I was wondering if this was the best way of doing this. Wouold this method create any problems, and is there a more efficient way of doing it. I know this is probably overkill just so I can go from dataContext.Products.SingleOrDefault<Product>(p => p.Id == productId) to Product.FromId(productId) but it's just for a bit of fun, I enjoy the challenge. :) Many thanks!
Dominic Pettifer Blog: www.dominicpettifer.co.uk