Art Of Programming

musings by Dmytrii Nagirniak

Playing With Linq2Sql - No INSERTs on SubmitChanges

I spent the whole evening trying to figure out what’s going on when I run the code:

   1: private static Product GetProduct(MyDbDataContext db)
   2: {
   3:     Product p = db.Products.FirstOrDefault(x => true);
   4:     if (p == null)
   5:     {
   6:         // Insert a a product if not available yet
   7:         p = new Product
   8:         {
   9:             Name = "PROD " + DateTime.Now.ToString()
  10:         };
  11:         db.Products.InsertOnSubmit(p);
  12:         db.UpdateDatabase();
  13:     }
  14:     return p;
  15: }

After I run the code and check the database there are no records available in the table.
What can be wrong with this really simple code? (Well, I’m just playing with it so there’s lots of place of improvement).

The answer is nothing. It is a console application and uses a database copied to Debug directory. So the debug database is used instead of the one you design and work with.


  1. User absolute path in the connection string. So instead of this one "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MyDb.mdf;Integrated Security=True;User Instance=True" use something like "Data Source=.\SQLEXPRESS;AttachDbFilename=|D:\YourPath\MyDb.mdf;Integrated Security=True;User Instance=True"
  2. Override DataDirectory at runtime (step 2 directories up from current path .\bin\Debug) using AppDomain.CurrentDomain.SetData("DataDirectory", Directory.GetParent(Directory.GetParent(Directory.GetCurrentDirectory()).FullName).FullName);
  3. Something else?

Thanks to this forum post for figuring it out.