【发布时间】:2010-11-24 02:53:45
【问题描述】:
我正在使用实体框架版本 1,并且我正在尝试创建一个通用存储库,但我找不到获取每个表的主键的方法。有人解决了这个问题吗?
更新:我的目标用途是使用如下所示的通用方法:
TModel GetByPrimaryKey(Guid key)
{
}
【问题讨论】:
标签: entity-framework generics repository-pattern
我正在使用实体框架版本 1,并且我正在尝试创建一个通用存储库,但我找不到获取每个表的主键的方法。有人解决了这个问题吗?
更新:我的目标用途是使用如下所示的通用方法:
TModel GetByPrimaryKey(Guid key)
{
}
【问题讨论】:
标签: entity-framework generics repository-pattern
最后,我从这里改编了@Marc 的答案:C# Linq-SQL: An UpdateByID method for the Repository Pattern
结果是这样的:
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);
}
...其中 _DB 是 DataContext。
我希望这对将来的某人有所帮助。
【讨论】:
你必须使用某种反射。
试试这样的:
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;
}
【讨论】: