简体   繁体   中英

C# - SaveChanges() doesn't update the database

I tried many solutions found on Stackoverflow but none worked. I have a local database linked with EF Designer.

I'm using Entity Framework to create rows and store them into the database. It's working since database.SaveChanges(); returns 1 (not zero). Then I loop on the database rows and I can see that data were well saved.

Nonetheless, when I'm closing my console app and refreshing database, I can't find the values I just added and the rows I generated.

Working on this issue since few hours, browsed Internet but none of the answers helped me.

I already tried to do database.User.Attach() and EntityState.Modified but they didn't work.

I even tried to move my code in a different class, but it didn't work.

public static void AddClient(String firstName, String lastName, int phoneNumber, String email, String wishlist)
{
    using (DatabaseEntity database = new DatabaseEntity())
    {
        database.User.Add(new User() {
                First_Name = firstName,
                Last_Name = lastName,
                Phone_Number = phoneNumber,
                Email = email,
                Wishlist = wishlist
            });

        database.SaveChanges();
    }
}

I expected data to be saved in the database after closing app, but they aren't.

I found the solution.

When Visual Studio uses local databases, at each debug it copies the databases and works on the copied.

So, I had to add a new connection on the Server Explorer that was targetting my_project_path/bin/debug/database.mdf

Then, I had to edit one of its properties which was Copy to Output Directory . Its new value is now Copy if Newer and now my datas are well saved in the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM