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);
精彩评论