Overnight, from a server somewhere in the US.
#whattookyousolong
Overnight, from a server somewhere in the US.
#whattookyousolong
I?ve been learning (read ?figuring out?) how to use Linq and SQL these past few days and I?m really surprised as to how easy it makes things.
Take this example for instance:
1: private int GetNextTQNo(string Project)2: {3: int NextTQNo = 0;4: SqlConnection tmpconn = new SqlConnection(5: "server=bas047\\AUTODESKVAULT;"6: + "Database=TQDetails;Integrated Security=SSPI;Connection Timeout=200");7: tmpconn.Open();8: SqlCommand cmd = tmpconn.CreateCommand();9: CFQ.SelectQueryBuilder query = new CFQ.SelectQueryBuilder();10: query.SelectFromTable("Details");11: query.SelectAllColumns();12: query.AddWhere("Project", CFQ.Enums.Comparison.Like, Project, 1);13: query.AddOrderBy("No", CFQ.Enums.Sorting.Descending);14: cmd.CommandText = query.BuildQuery();15: SqlDataAdapter da = new SqlDataAdapter(16: cmd.CommandText, tmpconn.ConnectionString);17: DataSet ds = new DataSet();18: da.Fill(ds, "Details");19: foreach (DataTable Dtable in ds.Tables)20: {21: foreach (DataRow Drow in Dtable.Rows)22: {23: foreach (DataColumn Dcolumn in Dtable.Columns)24: {25: if (Dcolumn.ColumnName == "No")26: {27: NextTQNo = (int)Drow[Dcolumn];28: NextTQNo += 1;29: return NextTQNo;30: }31: }32: }33: }34: tmpconn.Close();//close the sqlconnection35: tmpconn = null;//empty the sqlconnection36: return NextTQNo;37: }?
With Linq this becomes:
1: private int GetNextTQNo(string Project)2: {3: int no = 0; // initial value.4: DataContext db = new TQFormDataContext();5: var q =6: from a in db.GetTable<Detail>()7: where (a.Project == Project)8: orderby a.No descending9: select a.No;10: foreach (var a in q)11: {12: no = a;13: return no;14: }15: if (no != 0)16: {17: no += 1;18: }19: else20: {21: no = 1;22: }23: return no;24: }I think the Linq approach is a lot simpler ? assuming of course that it works!
I?m surprised that more developers don?t use Linq for connection to their databases.
I have recently been creating an increasing number of applications for the project/office here, and think I?d quite like to start sharing some of what I?ve learnt along the way.
A lot of the time, the code I write is cobbled together from examples/ideas I glean from the interweb ? primarily thanks to Google.
Anyway, I hope to start updating the site with some longer posts that aren?t simply grabbed from my Twitter account.
Hopefully this will also enable me to consolidate what I?ve already learnt.
I guess we?ll see.