I recently had a simple query that runs super quick in SSMS that was taking way, way too long to run using the Entity Framework in my C# program.
This page has been extremely helpful, when trouble shooting EF performance problems in general:
https://www.simple-talk.com/dotnet/net-tools/entity-framework-performance-and-what-you-can-do-about-it/
..but in this case, nothing helped. So in the end, I did this:
List<UpcPrintingProductModel> products = new List<UpcPrintingProductModel>();
var sql = "select top 75 number, desc1, upccode "
+ "from MailOrderManager..STOCK s "
+ "where s.number like @puid + '%' "
;
var connstring = ConfigurationManager.ConnectionStrings["MailOrderManagerContext"].ToString();
using (var connection = new SqlConnection(connstring))
using (var command = new SqlCommand(sql, connection)) {
connection.Open();
command.Parameters.AddWithValue("@puid", productNumber);
using (SqlDataReader reader = command.ExecuteReader()) {
while (reader.Read()) {
var product = new UpcPrintingProductModel() {
ProductNumber = Convert.ToString(reader["number"]),
Description = Convert.ToString(reader["desc1"]),
Upc = Convert.ToString(reader["upccode"])
};
products.Add(product);
}
}
}
(For this particular query, I just completely bypassed the EF altogether, and used the old standby: System.Data.SqlClient.)
You can wrinkle your nose in disgust; I certainly did - but it didn't actually take that long to write, and it executes almost instantly.