代码之家  ›  专栏  ›  技术社区  ›  Remus

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

  •  0
  • Remus  · 技术社区  · 14 年前

    我使用的是实体框架版本1,我试图创建一个通用存储库,但是我找不到获取每个表的主键的方法。有人解决了这个问题吗?

    更新:我的目标用途是使用一个如下所示的泛型方法:

    TModel GetByPrimaryKey(Guid key)
    {
    
    }
    
    2 回复  |  直到 14 年前
        1
  •  3
  •   Community CDub    8 年前

    最后,我从这里改编了@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 .

    我希望这对将来的人有帮助。

        2
  •  0
  •   RPM1984    14 年前

    你必须用某种反射。

    试试这样的:

    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;
    }