Entity Framework: Generic Repository and Table Primary Keys
I'm using Entity Framework version 1, and i'm trying to create a generic repository, but I can't find a way to get the Primary Key of each table. Has anyone solved this issue?
UPDATE: My target use for this would be for a generic method th开发者_Python百科at looks like this:
TModel GetByPrimaryKey(Guid key)
{
}
In the end, I adapted @Marc's answer from here: C# Linq-SQL: An UpdateByID method for the Repository Pattern
The result is something like this:
public TModel GetByPrimaryKey(Guid key)
{
// get the row from the database using the meta-model
MetaType meta = _DB.Mapping.GetTable(typeof(TModel)).RowType;
if (meta.IdentityMembers.Count != 1) throw new InvalidOperationException("Composite identity not supported");
string idName = meta.IdentityMembers[0].Member.Name;
var param = Expression.Parameter(typeof(TModel), "row");
var lambda = Expression.Lambda<Func<TModel, bool>>(
Expression.Equal(
Expression.PropertyOrField(param, idName),
Expression.Constant(key, typeof(Guid))), param);
return _DB.GetTable<TModel>().FirstOrDefault(lambda);
}
...where _DB is a DataContext
.
I hope this helps someone in the future.
You have to use some kind of reflection.
Try something like this:
private PropertyInfo GetPrimaryKeyInfo<T>()
{
PropertyInfo[] properties = typeof(T).GetProperties();
foreach (PropertyInfo pI in properties)
{
System.Object[] attributes = pI.GetCustomAttributes(true);
foreach (object attribute in attributes)
{
if (attribute is EdmScalarPropertyAttribute)
{
if ((attribute as EdmScalarPropertyAttribute).EntityKeyProperty == true)
return pI;
}
else if (attribute is ColumnAttribute)
{
if ((attribute as ColumnAttribute).IsPrimaryKey == true)
return pI;
}
}
}
return null;
}
精彩评论