How can I programmatically get the primary key for an object (in Entity Framework 4)?

I have this base abstract class that implements a repository template

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 the primary key column (corresponding property) to implement the FyndByID method .

Suggest that the priamry key is not , but an int data type

+3
source share
1 answer

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

[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);
0

Source: https://habr.com/ru/post/1751886/


All Articles