Edit: Conrad is better because it is so much easier. The solution below works, but is only required in situations like ObjectDataSource, where the class method is retrieved through reflection without raising the inheritance hierarchy. Obviously this is not happening here.
This is possible, I had to implement a similar template when I developed a custom user solution for working with ObjectDataSource:
public interface IPrimaryKey<T> where T : IPrimaryKey<T> { int Id { get; } } public static class IPrimaryKeyTExtension { public static IPrimaryKey<T> GetById<T>(this IQueryable<T> source, int id) where T : IPrimaryKey<T> { return source.Where(pk => pk.Id == id).SingleOrDefault(); } } public class Person : IPrimaryKey<Person> { public int Id { get; set; } }
Fragment of use:
var people = new List<Person> { new Person { Id = 1 }, new Person { Id = 2 }, new Person { Id = 3 } }; var personOne = people.AsQueryable().GetById(1);
cfeduke
source share