You can use the general method with interface restriction.
When you have these automatically generated POCO classes:
public partial class Product1 { public string Column1 { get; set; } public string Column2 { get; set; } } public partial class Product2 { public string Column1 { get; set; } public string Column2 { get; set; } } public partial class Product3 { public string Column1 { get; set; } public string Column2 { get; set; } }
You are creating an interface for properties that have entity classes ...
interface IProduct { string Column1 { get; set; } string Column2 { get; set; } }
... which you apply to your generated classes (in new code files - classes are partial so you can do this):
partial class Product1 : IProduct {}; partial class Product2 : IProduct {}; partial class Product3 : IProduct {};
Now you can create a generic method for your request. You can do this with an extension method to apply it to your DbSet s:
static class ProductExtensions { public static List<T> GetProducts<T>(this DbSet<T> products) where T : IProduct { var productQry = from product in products where product.Column1 == "Example" select product; return productQry.ToList(); } }
This extension method can be used on DbSet s:
List<Product1> product1List = context.Product1s.GetProducts(); List<Product2> product2List = context.Product2s.GetProducts(); List<Product3> product3List = context.Product3s.GetProducts();
The only limitation you have is that the columns in your tables really need to have the same name and type. EF does not recognize explicit interface implementations. On the other hand, tables do not have to be completely identical. You can define an interface for part of the columns (which must match), and the rest can be different.
Sefe
source share