Hello,
I am trying to come up with a GetById method for a generic repository wrapper. My PK ids can be ints or guids. For example, I found something similar:
public override T GetById(object id)
{
var itemParameter = Expression.Parameter(typeof(T), "item");
var whereExpression = Expression.Lambda<Func<T, bool>>
(
Expression.Equal(
Expression.Property(
itemParameter,
typeof(T).GetPrimaryKey().Name
),
Expression.Constant(id)
),
new ParameterExpression[] { itemParameter }
);
var item = GetAll().Where(whereExpression).SingleOrDefault();
if (item == null)
{
throw new Exception(string.Format("No {0} with primary key {1} found",
typeof(T).FullName, id));
}
return item;
}
This issue is that the GetPrimaryKey extension method does not seem to work for LLBLGen entities.
Here’s the code for the extension:
public static class TypeExtensions
{
public static PropertyInfo GetPrimaryKey(this Type entityType)
{
foreach (PropertyInfo property in entityType.GetProperties())
{
if (property.IsPrimaryKey())
{
if ((property.PropertyType != typeof(int)) && (property.PropertyType != typeof(Guid)))
{
throw new ApplicationException(string.Format("Primary key, '{0}', of type '{1}' is not int or guid",
property.Name, entityType));
}
return property;
}
}
throw new ApplicationException(string.Format("No primary key defined for type {0}", entityType.Name));
}
public static bool IsPrimaryKey(this PropertyInfo propertyInfo)
{
var columnAttribute = propertyInfo.GetAttributeOf<ColumnAttribute>();
if (columnAttribute == null) return false;
return columnAttribute.IsPrimaryKey;
}
public static TAttribute GetAttributeOf<TAttribute>(this PropertyInfo propertyInfo)
{
object[] attributes = propertyInfo.GetCustomAttributes(typeof(TAttribute), true);
if (attributes.Length == 0)
{
return default(TAttribute);
}
return (TAttribute)attributes[0];
}
}
Is there a better way to accomplish this? I don’t like the reflection and I don’t think the GetCustomAttributes call will work for LLBLGen entities.
Any suggestions?
Thanks,
Rick