There is a banal sign
enter image description here

It was created as a local database (.mdf)
I am writing an addendum:

ProjEntities context = new ProjEntities(); context.Tables.Add(new Table { ProductName = "Book", Price = 85 }); context.SaveChanges(); 

Changes were not added to the database. Although, if immediately after saving from the context to select entries in the list, the added entry is.

  • Connection is not relevant already. It works again. And the data that is in the database - selects. And new ones do not get into the database. - TheOwl
  • The database is local, during the build it is re-copied from the project folder to the bin folder, overwriting the saved data? - PashaPash
  • @TheOwl at what point are the data lost? After restarting the application? - PashaPash

1 answer 1

A local database is usually meant to connect to SQL Express / SQL Local DB with the indication AttachDBFileName = |DataDirectory|\mydatabase.mdf .

|DataDirectory| in the case of a non-ASP.NET application, it means "that folder in which the exe file is located." Those. this is most likely not the project folder in which the sources are located, but the bin folder.

Those. when specifying the path via |DataDirectory| the program does not work with the mdf file added to the project, but with its copy in the bin.

This is not specific to EF, the same thing happens when you manually work with SQL through ADO.NET.

Therefore, with this method of connection, there are usually two related problems.

  • Problem 1: The changes made by the program are "not visible" in the database.
    Reason: the program works with a copy of the file in bin, and the developer checks the original in the project folder for changes.
    Solution: fixed by viewing the file from bin.

  • Problem 2: changes made by the program are lost when the program is restarted from the studio (by F5 / Ctrl + F5 ).
    Reason: - The default mdf file is added to the project with Build Action = Content, and by setting the Copy To Output Folder = Always. This means that when an application is rebuilt (when it is restarted from the studio), the database file from the project is copied to the bin folder, replacing the file that was located there, into which the data was saved during the last launch.
    Solution: fixed by changing the Copy To Output Folder value for the mdf file in the project to If Newer .