Tamal Banerjee
Tamal Banerjee

Reputation: 503

Data not saving in local database on re run c#

I've created a basic windows form application using the Service-based Database option so that when I deploy it on another pc it will not require to install sql server there.Here is the image of my app

I've added a LINQ-to-SQL class in the project and here is my full code

And here is the app.config file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
  <connectionStrings>
    <add name="_16Sep18_databaseAppWithSetup_.Properties.Settings.WrestlersConnectionString"
      connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Wrestlers.mdf;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

The problem is when every time I run my program the previously stored data is no longer in the database but when I input data and perform the insert,delete,update etc operations it works and the data is shown in the datagridview also but once I close the app all those data are gone. Why is this happening and how do I fix it?

Upvotes: 1

Views: 2623

Answers (3)

Hồ Kim Long Sơn
Hồ Kim Long Sơn

Reputation: 101

I resolved this problem by changing "copy always" => "copy if newer":

enter image description here

It worked for me. Hope this helps you.

Upvotes: 2

Ahmed Kamal
Ahmed Kamal

Reputation: 85

This problem occurs because the mdf file is saving in DEBUG folder also when you try to run the program... Just go to app.config file,, it seems like you have added the directory like

Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Data\Database1.mdf;Integrated Security=True;User Instance=True

change the |DataDirectory| to full data directory address like

"AttachDbFileName=c:\Project\Data\Database1.mdf"

it will work

Upvotes: 2

ErikEJ
ErikEJ

Reputation: 41769

The MDF file is copied to the debug folder on each run, and that is the file your code manipulates, not the one in your source folder.

Upvotes: 1

Related Questions