[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 248
  • Last Modified:

How to persist inserted records in an .MDF file? Inserted records dissappear.

How do you persist data in an .MDF file?  I created an app that has a data source to an sql .MDF file, but I am not using the server (kind of like using an access database file).  I execute this code with no error, but when I close the app and open it again, the data is not in the table.  Why would this be?

My test code is like this

            SqlConnection myConn = new SqlConnection(s.ConnectionString);

            for (int i = 0; i < 1000; i++)
                string SQL = "INSERT INTO TEST_TABLE (FIELD1, FIELD2, FIELD3)" +
                             " VALUES ('TestData1'," +
                             "'TestData3'," +

                SqlCommand ins = new SqlCommand(SQL, myConn);
  • 2
1 Solution
Daniel WilsonCommented:
Reading / Writing the .MDF file directly is not supported.

I don't know why no error was raised and I don't know how you're reading the file to verify what's in it.  But if you're going to use SQL Server, you need to talk to the server!

With Access, you're not doing direct file reading/writing either.  But to get the database stuff (Jet, I think it still is) to know what database you talk to, you tell it the file.  You're still using the installation of the DBMS.
DanielWilson might be on to something, but there is another typical mistake when working with MDF files.

If you're wokring in a Visual Studio project, ensure that the mdf file that is part of your project is not set to "Deploy - Copy Always".  Otherwise, every time you restart your app the database will be overwritten with a fresh (and empty) copy.
Oh, to check this, right-click the MDF file in Visual Studio, and select "Properties".  This option is in the Properties window.

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now