Is there a way to use generic methods with Entity Frameworks?
For instance, I have the tables: TblPlan and TblTier. Can I pass these in a generic method and find the type? Each table have slightly different values and I want to compare the values differently for each. I tried:
public static Dictionary<T, List<T>> checkDuplicates<T>(T something)
{
try
{
//TblCommissionPlan plan = (TblCommissionPlan)something;
//var type = typeof(something);
}
}
These didn’t work…any ideas?
That is not a purpose of generic methods. If you write a method which has signature:
you are defining “a shared logic”. It means that the same logic must work for every
Tpassed to the method. If it doesn’t you must constraint theTby using some kind of constraint:Now you know that every
Tpassed to the method must implementISomeInterfaceand you can use in your method any property or method declared on that interface.Content of the method is not supposed to be different for different type of
Tbut logic can because you can callTs methods and properties which can have different implementation. If it is not enough you can pass another parameter – generic delegate or some another generic class based onTwhich will add some additional logic for you.In you scenario you want to compare each passed class differently => comparison cannot be part of your method but it must either be part of your entities or you must pass additional class / method which will do the comparison for the method.
For implementing comparison directly in your classes you can implement
IComparable<T>interface and declare your method as:For implementing comparison outside of your classes you can simply use
Func<T, T, int>or implementation ofIComparer<T>:In either case I’m not sure how does this relate to entity framework because signature of your method has nothing to do with EF.