0

I'm using a LocalDB database with EntityFramework on an ASP.NET MVC project.

How can I simulate a connection failure to test the following try...catch block?

try
{
   if (ModelState.IsValid)
   {
      db.Entry(course).State = EntityState.Modified;
      db.SaveChanges();
      return RedirectToAction("Index");
   }
}
catch (DataException)
{

   ModelState.AddModelError("", "Unable to save changes.");
}

I've tried trying to take the database offline in SQL management studio, but it just hangs. I can't stop the SQL service as LocalDB doesn't run as a service.

Evonet
  • 3,600
  • 4
  • 37
  • 83

2 Answers2

1

You can stop a LocalDB instance even though it doesn't run as a service, you can use the SQLLocalDB.exe tool to do this:

SqlLocalDB Utility

steoleary
  • 8,968
  • 2
  • 33
  • 47
  • Except everytime I stop the instance, and then run my code, LocalDB starts back up again...! – Evonet Sep 06 '13 at 10:35
1

Have you tried giving it a non-existing name of LocalDB instance? Just put this in your connection string for this test:

Server=(localdb)\missing_instance`

(if you embed this connection string in code don't forget to escape the \ character :-))

connectionString="Server=(localdb)\\missing_instance;..."
Krzysztof Kozielczyk
  • 5,887
  • 37
  • 28