A lambda implementation of GetEntity

Developer
Feb 12, 2009 at 10:51 AM
        [System.ComponentModel.DataObjectMethod(System.ComponentModel.DataObjectMethodType.Select)]
        public static TEntity GetEntity(object id)
        {
            string query = string.Format("Select * from {0} where {1} = {2}", new object[] { TableName, PrimaryKeyDBColumnName, id });
            return DataContext.ExecuteQuery<TEntity>(query).FirstOrDefault();
            
        }

        [System.ComponentModel.DataObjectMethod(System.ComponentModel.DataObjectMethodType.Select)]
        public static TEntity GetEntity(object id)
        {
            var table = DataContext.GetTable<TEntity>();
            var mapping = DataContext.Mapping.GetTable(typeof(TEntity));
            var pkfield = mapping.RowType.DataMembers.SingleOrDefault(d => d.IsPrimaryKey);
            if (pkfield == null)
                throw new Exception(String.Format("Table {0} does not contain a Primary Key field", mapping.TableName));

            var param = Expression.Parameter(typeof(TEntity), "e");
            var predicate = Expression.Lambda<Func<TEntity, bool>>(Expression.Equal(Expression.Property(param, pkfield.Name), Expression.Constant(id)), param);

            return table.SingleOrDefault(predicate);
        }