I am creating an Intranet website with ASP.NET MVC and Onion Architecture. I have been implementing the repository pattern but I have a difficulty.
You're calling the Queryable.SingleOrDefault method.
Its second parameter has the type Expression<Func<T, bool>> so you can build expression manually, using as identifier property as you wish.
Short example:
public T Get(long id)
{
var idName = "ID" + typeof(T).Name; // For Document would be IDDocument
var parameter = Expression.Parameter(id.GetType());
var property = Expression.Property(parameter, idName)
var idValue = Expression.Constant(id, id.GetType());
var equal = Expression.Equal(property, idValue);
var predicate = Expression.Lambda<Func<T, bool>>(equal, parameter);
return entities.SingleOrDefault(predicate);
}
Imagine you wrote lambda function (T obj) => obj.IdProperty == id.
Here obj is parameter, and idName should store "IdProperty" string.
property means obj.IdProperty, idValue means the value if id.
equal means obj.IdProperty == id, and predicate means whole expression (T obj) => obj.IdProperty == id.