【问题标题】:How I can programmatically retrieve a primary key for an entity (in Entity Framework 4)?如何以编程方式检索实体的主键(在 Entity Framework 4 中)?
【发布时间】:2010-06-26 13:46:34
【问题描述】:

我有这个实现存储库模式的基本抽象类

public abstract class Repository<T> : IRepository<T> where T : class
    {
        private ObjectSet<T> _entitySet;
        private ObjectContext _dataContext;

        public Repository(ObjectContext context)
        {
            _dataContext = context;
            _entitySet = _dataContext.CreateObjectSet<T>();
        }

        public T FindByID(int id)
        {
          //??????

        }
    }

现在我需要知道主键列(对应属性)来实现 FyndByID 方法。

建议主键不是复合的,它的数据类型是int

【问题讨论】:

  • 它是否必须与数据库无关,或者特定于 SQL Server 的版本是否适合您?

标签: entity-framework repository repository-pattern


【解决方案1】:

实体类的一个关键属性用这个属性标记:

[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]

请注意,EntityKeyProperty 设置为 true。为类型为T 的具有此属性的属性找到此属性,并将其值与传递的id 进行比较:

//Property that holds the key value
PropertyInfo p = typeof(T).
GetProperties().FirstOrDefault(
    x => x.GetCustomAttributes(typeof(EdmScalarPropertyAttribute), false)
          .OfType<EdmScalarPropertyAttribute>()
          .Where(y => y.EntityKeyProperty == true)
          .Count() > 0);

//Return first item having the passed id or null
return _entitySet.FirstOrDefault(x => (int)p.GetValue(x, null) == id);

【讨论】:

  • 你的T类型的类是实体框架生成的吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-05
  • 1970-01-01
  • 1970-01-01
  • 2016-05-10
相关资源
最近更新 更多