You can use a generic method with an interface constraint.
When you have these auto-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 create an interface for the properties the entity classes have in common...
interface IProduct {
string Column1 {
get;
set;
}
string Column2 {
get;
set;
}
}
...which you apply to your generated classes (in new code files - the classes are partial to allow you to do that):
partial class Product1 : IProduct {};
partial class Product2 : IProduct {};
partial class Product3 : IProduct {};
Now you can create a generic method for your query. You can make it 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();
}
}
You can use this extension method on your DbSet
s:
List<Product1> product1List = context.Product1s.GetProducts();
List<Product2> product2List = context.Product2s.GetProducts();
List<Product3> product3List = context.Product3s.GetProducts();
The only restriction that 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, the tables don't have to be completely identical. You can define an interface for a part of the columns (which have to match) and the rest can be different.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…