【问题标题】:Entity Framework: Generic Repository and Table Primary Keys实体框架:通用存储库和表主键
【发布时间】:2010-11-24 02:53:45
【问题描述】:

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

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

TModel GetByPrimaryKey(Guid key)
{

}

【问题讨论】:

    标签: entity-framework generics repository-pattern


    【解决方案1】:

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

      你必须使用某种反射。

      试试这样的:

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

      【讨论】:

      • 谢谢 - 我应该从一开始就更清楚。我的目标是在“getbyprimarykey”通用方法中使用这些信息。我已经更新了问题。
      • @Remus - 看看这个 SO 答案:stackoverflow.com/questions/2958921/… 虽然不能 100% 确定它是否适用于 EF1。
      • 这有帮助。我注意到您发送给我的链接使用了 OjbectContext,而我有一个 DataContext。关于将解决方案移植到使用 DataContext 的 VS 生成模型的任何提示?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-11
      相关资源
      最近更新 更多