Entity Framework won't persist data in SQL Express (MDF)

后端 未结 4 1172
醉酒成梦
醉酒成梦 2021-01-02 03:20

I was developing an application using Entity Framework and storing data in a .mdf database. My code can read the data, apparently it can save too, but only apparently. It ge

4条回答
  •  旧时难觅i
    2021-01-02 03:24

    This situation can arise due to the way you attach an MDF database file to LocalDB, using the Visual Studio Server Explorer.

    When you attach an MDF file, VS asks if you want create a copy of the database in your project. If you say "No" then a connection string is generated in the config file which includes an "attachdbfilename" entry which points to the absolute path to the MDF file on disk (e.g. "C:\..."). However, if you say "Yes" then it makes a copy of the MDF file, adds it to the project, and the "attachdbfilename" entry in the generated connection string becomes relative to |DataDirectory|.

    When you hit F5 to run the application, VS copies all of the files including the database MDF file to the bin folder. All changes are made to that database. When you close and restart the application, a new clone of the original database is copied to the bin folder, overwriting anything that was there, so appearing to overwrite your previous changes. This is covered in How to: Manage Local Data Files in Your Project

提交回复
热议问题