Posts Tagged ‘linq to sql’

Linq to sql, ctx.submitchanges progress

January 2, 2011 1 comment

Linq to sql provides no default mechanism for tracking progress of the ctx.submitchanges() method.

This can be troublesome if you are using batch import with linq to sql (which is not the best practice by itself).

I asked question on the stackoverflow

Response to the similar question was to divide inserts into multiple ctx.submitchanges() methods. This would work fine, but I needed transactions (all inserts or none)

I can get total number of inserts by using ctx.GetChangeSet().Inserts.Count;

Using ActionTextWriter class I found on

I was able to track progress of the inserts using following snippet of code

ctx.Log = new ActionTextWriter(s => {
  if (s.StartsWith("INSERT INTO"))

Linq to sql will write to the log file every sql statement. if the statements begins with INSERT INTO, that’s new insert.

Evertything I need for the progress bar is here 🙂

Also, performance wise, I’m reporting progress for every 10 000 inserted records. Refreshing screen too often can be slow sometimes.


LinqToSql Sum over empty collection causes exception

October 15, 2010 Leave a comment

Linq to Sql Sum method over empty collection returns null. Linq to object Sum method over empty collection returns 0.

This Linq To Sql behavior can cause exception :

"The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type."

This will happen if you try to assign sum to decimal. Decimal is not nullable. If sum is called over empty collection (e.g. no items are return from where clause) sum will try to return null. decimal is not nullable and you have exception Sad smile

One solution is to cast sum so it returns nullable decimal (decimal ?), Second solution is to use linq to object, because, linq to object sum over empty collection returns 0.

Why is all this happening?

In SQL, Sum() aggregate operator returns null for an empty set. So this is as designed.

Since users often rely on LINQ to SQL producing the same results as an equivalent SQL query, we decided not to convert the null to zero as in case of LINQ to Objects. There are a number of cases where we considered forcing .NET/C#/VB semantics for consistency with LINQ to Objects vs retaining SQL semantics for consistency with SQL. In most cases, we favored the latter for consistency and more enforceable and performant implementation,




You can read more about this issue on