Basic Entity Framework and Local Database, unable to add a record

394 views Asked by At

It has been a couple of years since I used Entity Framework, so maybe my brain is mud, but I cannot add a record to persist to a simple database.

The database is a "Local Database" but I am not doing code first. It has two tables, Tab3 and Tab4. Tab3 has columns Id (unique, primary key, Identity) and Col1 (nvarchar, allow nulls), col2 (nvarchar, allow nulls). This is populated with two rows. The edmx model and mappings look good to me. This should be a simple setup.

The code is this:

            using (DBMod1Entities1 context = new DBMod1Entities1())
            {
                Tab3 t3 = new Tab3();
                t3.Col1 = "e";
                t3.Col2 = "3";
                context.Tab3.Add(t3); 
                int res = context.SaveChanges();
                Debug.WriteLine("Results from SaveChanges() " + res.ToString() );
                int cnt = context.Tab3.Count();
                Debug.WriteLine("Count records " + cnt);
            }

it runs and dumps to output:

Results from SaveChanges() 1
Count records 3

If I call this:

        using (DBMod1Entities1 context = new DBMod1Entities1())
        {
            int cnt = context.Tab3.Count();
            Debug.WriteLine("Count records " + cnt);
        }

I get the expected:

Count records 3

If I keep adding silly records, the counts keep going up, as expected.

BUT if I restart the program, the data is not in the Local Database. The original two records remain in the database, but the records I added were not persisted.

What am I doing wrong?

1

There are 1 answers

0
rwg On

I actually found the answer here: Database file .sdf does not update after closing application

The short explanation is that by default, the "Local Database" is copied to the BIN folder every time the program is started from Visual Studio, therefore replacing the previous run's data. I disabled the "copy" in the properties, and changed my app.config to point to the database I wanted to update.