views:

41

answers:

1

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 property) to implement FyndByID method.

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

A: 

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);
Simon
p = null something is wrong...
VoimiX
Has your class of type T been generated by the entity framework?
Simon
Of course,http://xmages.net/storage/10/1/0/9/3/upload/8ed7e7e1.jpg
VoimiX