I have the following code. It runs fine.
In the place I have marked I'd like to write a query (I assume with LINQ
) which extracts the CompanyName
where
the MainKey == 3028
I suspect this is trivial but I'm new to LINQ
and I've looked up some basic LINQ
info on MSDN and can't seem to get it to work.
namespace EntityFrameworkExperiment {
class Program {
static void Main(string[] args) {
var models = SelectTop100Models("SELECT top 100 * FROM WH.dbo.vw_DimXXX");
Console.Write("hello world");
//<<<<<<<linq query to pull out companyname when MainKey == 3028
Console.Read();
}
static IEnumerable<MyModel> SelectTop100Models(string myCommandText) {
var connectionString = ConfigurationManager.ConnectionStrings["XXX"].ConnectionString;
using(var conn = new SqlConnection(connectionString))
using(var cmd = conn.CreateCommand()) {
conn.Open();
cmd.CommandText = myCommandText;
using(var reader = cmd.ExecuteReader()) {
while(reader.Read()) {
yield return new MyModel {
MainKey = reader.GetInt32(reader.GetOrdinal("MainKey")),
ServerId = reader.GetInt32(reader.GetOrdinal("ServerId")),
CompanyId = reader.GetInt32(reader.GetOrdinal("CompanyId")),
CompanyName = reader.GetString(reader.GetOrdinal("CompanyName")),
};
}
}
}
}
}
public class MyModel {
public int MainKey { get; set; }
public int ServerId { get; set; }
public int CompanyId { get; set; }
public string CompanyName { get; set; }
}
}
Add using System.Linq
The query should be
var companyName = models
.Where(o => o.MainKey == 3028) // apply the filter
.Select(o => o.CompanyName) // tell it you only need the one property
.FirstOrDefault(); // take the first result it finds or use 'null' if the MainKey does not exist
But there is one thing you have to remember - here you are not using LINQ queries to the SQL server - instead you are retrieving all data in memory and then filtering them in .NET. What this means is that if the database contains millions of rows, they will all be pulled from the SQL server. You are applying TOP 100 but that will get you into trouble if the key 3028 is not within the first 100.
What you should be doing is creating a model using Entity Framework (or a similar tool) and then writing a query that target the classes generated by it. The good thing though is that the LINQ query will be exactly the same - it will just be translated to SQL behind the scenes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With