开发者

How I can programmatically retrieve a primary key for an entity (in Entity Framework 4)?

开发者 https://www.devze.com 2023-01-04 16:35 出处:网络
I have this base abstract class which implements repository pattern public abstract class Repository<T> : IRepository<T> where T : class

I have this base abstract class which implements repository pattern

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)
        {
          //??????

        }
    }

Now I need to know primary key column (corresponding proper开发者_JS百科ty) to implement FyndByID method.

Suggest that priamry key is not composite and it's datatype is int


A key property of an entity class is marked with this attribute:

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

Note that the EntityKeyProperty is set to true. Find this attribute for the property with this attribute for the type T and compare its value with the passed 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);
0

精彩评论

暂无评论...
验证码 换一张
取 消