Generic extension method

I am working on this mvc project after Rob Connery shop video series and applying techniques. In filtering and extension methods, I started repeating a lot, for example:

public static Sponsor WithID(this IQueryable<Sponsor>qry, int ID)
{
    return qry.SingleOrDefault(s => s.ID== ID);
}

public static Keyword WithID(this IQueryable<Keyword>qry,int ID)
{
    return qry.SingleOrDefault(s => s.ID== ID);
}
....

      

To prevent this, I'm trying to write a generic extension like this:

public static T WithID<T>(this IQueryable<T>qry,int ID)
{
    return qry.SingleOrDefault(s=>ID==ID);
}

      

however s has no identifier, so how would you solve this?

0


a source to share


2 answers


You will need an interface that will declare an ID property like

public interface IInt32Identifiable
{
    public int ID { get; }
}

      

Then you can write:



public static T WithID<T>(this IQueryable<T> source, int id)
    where T : IInt32Identifiable
{
   return source.SingleOrDefault(s=> s.ID == id);
}

      

Of course, you will need to inject all the appropriate interface classes, but this is usually easy; if the classes are created by the constructor you probably want to use partial classes.

+5


a source


You will need two different extension methods. One for types that have an identifier, and one for types that don't. You will also need an interface or abstract base class that implements all ID'd types. Otherwise, the compiler won't let you dereference the ID.



The only alternative I can think of would require reflection to query the type for the ID property, and if it exists, get the value.

0


a source







All Articles