Entity framework doesn't save data entries in database

Monoloox picture Monoloox · Sep 7, 2011 · Viewed 10.9k times · Source

At first I should mention that this problem only occurs in windows forms applications and the same program in web mode for example with MVC3 works perfect.

Some days ago I wrote a very simple windows form program using Visual studio 2010 ultimate with a SQL Express database. I added the database by choosing Add > New item > Service-Based database and an entity data model based on this database in same way. I used Entity framework for adding some new records to tables. I had done such thing with VS 2008 SP1 before with no problem so I did the same. The program compiled and ran with no errors and I entered some new data. after exiting the program I came back to the database and nothing was happened. None of information I had entered had been saved. I debug the program step by step and everything was alright. The code below is related to a very simple program with mentioned problem. Database has one table (book):

namespace Book
{
    public partial class BookForm : Form
    {
        BookDatabaseEntities db = new BookDatabaseEntities();

        public BookForm()
        {
            InitializeComponent();
        }

        private void saveButton_Click(object sender, EventArgs e)
        {
            Book bookToCreate = new Book();

            bookToCreate.Id = Guid.NewGuid();
            bookToCreate.Title = titleTextBox.Text;

            db.Books.AddObject(bookToCreate);
            db.SaveChanges();
        }
    }
}

I'll be very grateful if anyone help me. Thanks in advance.

.................

After editing:

namespace Book
{
    public partial class BookForm : Form
    {
        //BookDatabaseEntities db = new BookDatabaseEntities();

        public BookForm()
        {
            InitializeComponent();
        }

        private void saveButton_Click(object sender, EventArgs e)
        {
            var db = new BookDatabaseEntities();
            var bookToCreate = db.Books.CreateObject();

            //Book bookToCreate = new Book();

            bookToCreate.Id = Guid.NewGuid();
            bookToCreate.Title = titleTextBox.Text;

            db.AcceptAllChanges();
            db.Books.AddObject(bookToCreate);
            db.SaveChanges();
        }
    }
}

Answer

Monoloox picture Monoloox · Sep 18, 2011

Finally after lots of searching and asking I found the solution in MSDN forums thanks to Patrice Scribe You can see it here