Programming‎ > ‎

LINQ

Here are some general tips for LINQ programming

Updated 7/8/2020

Index

Surprize! There are two versions of CompiledQuery.

I was surprised to find today (7/8/2020) that there are two versions of compiled queries. Both are not compatible

    
  System.Data.Entity.Core.Objects.CompiledQuery  <<<<<< default at VS2017 v.15.9.23    
  System.Data.Linq.CompiledQuery                 <<<<<< this is the familiar version
  

Head


What is the difference between SubmitChanges() in LINQToSQL vs. SaveChanges() in EntityFramework?

Here is the difference.

  
  EntityFramework:     
  SaveChanges operates within a transaction. SaveChanges will roll back    
  that transaction and throw an exception if any of the dirty ObjectStateEntry    
  objects cannot be persisted  
  LINQTOSQL:     
  SubmitChanges starts a transaction and will roll back if an exception occurs     
  while SubmitChanges is executing. However, this does not roll back the changes    
  in memory or tracked by the DataContext; those changes will need to be rolled     
  back manually. You can start with a new instance of the DataContext if the     
  changes in memory are to be discarded.
  

Head


How can I validate the build xml file?

Using LINQ2XML (XDOcument and XElement), it is easy to build xml file. Here is how to validate.

      
  XmlSchemaSet schemas = new XmlSchemaSet();
  bool fileExists = File.Exists(schemaFile);      
  if (fileExists == true)      
  {        
    try        
	{          
	  schemas.Add("http://mynamespace", schemaFile);        
	}        
	catch (Exception ex)        
	{          
	  MessageBox.Show(ex.ToString());          
	  return false;        
	}        
	bool res = false;        
	XDocument xDoc = XDocument.Load(xmlFileName);        
	xDoc.Validate(schemas, (o, e) =>        
	{          
	  statusLabel.Text = String.Format("Validation failed: line={0}, column={1}",                  
	  e.Exception.LineNumber, e.Exception.LinePosition);          
	  MessageBox.Show(e.ToString());          
	  res = true;        
	}
    );        
    if (res == false)          
	  statusLabel.Text = "Validation succeeded";      
  }
  

Head


Three ways to write join LINQ query where two tables are foreign key related.

LINQ to SQL allows an abbreviated syntax with . when two tables are foreignkey related, in addition toT-SQL syntax and SQL syntax. Here two tables called JOB and JOB_RUN_OPTION where JOB_ID in JOB is a foreign key in JOB_RUN_OPTIONS and JOB has RUN_JOB column with bool. dc is DataContext.

  
  // LINQ2SQL specific  
  var query1 = from j in dc.JOB_RUN_OPTIONs               
               where j.JOB.RUN_JOB == true                
               select j;  
  // T-SQL way  
  var query2 = from j in dc.JOBs               
               where j.RUN_JOB == true               
               from jro in dc.JOB_RUN_OPTIONs               
               where jro.JOB_ID == j.JOB_ID                
               select j;  
  // SQL way  
  var query3 = from j in dc.JOBs               
               join jro in dc.JOB_RUN_OPTIONs               
               on j.JOB_ID equals jro.JOB_ID               
               select j;
  

Head


How can I tell a particular attribute existence without try/catch?

An application configuration file contains many configuration. I needed a way tolook for a particular attribute. You can do try/catch, using Attribute("Name"). But this is a constly operation. Just use Any constructs as follows:

  
  bool res = setting.Attributes().Any(attrib=>attrib.Name=="field");
  
If true, then attribute ("field") exists in the configuration.

Head


How can I do double loop in LINQ?

Combining customer list and address list need double loop. Here is the way.

  
  var query = from n in customerList where n.Last == "Tosa"              
              join a in addressList               
              on n.AddressID equals a.ID              
              select new { n, a };  
  foreach (var item in query)  
  {    
    Console.WriteLine("Name {0} {1}, {2} {3} {4}",                       
	item.n.Last, item.n.First, item.a.Street, item.a.City, item.a.State);  
  }
  

Head


How can I do loop with LINQ?

LINQ creates IEnumerable output and thus you may be able to do loop with LINQ.


  // normal way      
  int[] ia = new int[10];      
  for (int i =0; i < ia.Length; ++i)        
   ia[i] = i*i;
  // LINQ way      
  int[] ib = (from i in Enumerable.Range(0, 10)                  
              select i*i).ToArray();
  

Head


How can I get LINQ to SQL debugging appear in Debug Window?

We always want to know what LINQ is doing and DataContext has a property called Log. Usually it is assigned to Console.Out but this works only under Console application. Thanks to Kris Vandermotten, he created DebuggerWriter so that you can assign to Log.

Update: the link to the Kris site is no longer working.  I put DebuggerWriter.cs in the attachment.  The usage is very easy.  You just new DebbuggerWriter instance and assign for the log, i.e. dc.log = dw;

Head

Top

Updated 7/15/2010

Yasunari Tosa,
Dec 8, 2011, 11:54 AM
v.1