实体框架:通用存储库和表主键

时间:2010-11-23 00:24:44

标签: entity-framework generics repository-pattern

我正在使用Entity Framework版本1,我正在尝试创建一个通用存储库,但我找不到获取每个表的主键的方法。有人解决了这个问题吗?

更新:我的目标用途是使用如下所示的通用方法:

TModel GetByPrimaryKey(Guid key)
{

}

2 个答案:

答案 0 :(得分:3)

最后,我从这里调整了@ 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

我希望将来可以帮助某人。

答案 1 :(得分:0)

你必须使用某种反思。

尝试这样的事情:

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;
}
相关问题