Entity Framework insert doesn't work

梦想与她 提交于 2019-12-25 18:26:37

问题


I have a very simple windows form project with Entity Framework.

Simply I draged my tables from "Data Source" tab in my "form" and it generate for me a "DataGridView" and a "BindingSource".

Data bound successfully and when I run project I can see "DataGridView" filled with data correctly and I can update any cells value from "DataGridView".

Problem is I can not insert any rows in my "DataGridView".

Here is some codes that I wrote hope it be useful to solve problem:

    Teachers_DBEntities context = new Teachers_DBEntities();

    private void SaveItem_Click(object sender, EventArgs e)
    {
        context.SaveChanges();
        MessageBox.Show("saved successfully");
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        teachers_tableBindingSource.DataSource = context.teachers_table.ToList();
    }

Upates for comments

I tested my "BindingSource" and found that it successfully understand if new record insert in "DataGridVeiw", but changes won't apply in database when I call context.savechanges();

context.savechanges() works fine when I update a cell, but it doesn't work when I try to insert a new record in my "DataGridView".

In my edmx file I mapped all columns correctly and primary key StoreGeneretedPattern property is set to Identity and its Entity Key property is set to true. Its auto-increment property in my SQL Server database file is set to true.

any help is appreciated.


回答1:


context.savechanges() works fine when I update a cell, but it doesn't work when I try to insert a new record in my "DataGridView".

What do you mean by "it doesn't work"? New record does not appear in database? Of course it won't.

In this line

teachers_tableBindingSource.DataSource = context.teachers_table.ToList();

you're breaking DataSource's connection to context. Any new item inserted into it will be inserted not into teachers_table, but into List you created over it.




回答2:


using (var context = new YourEntities ()) 
{
     var dpt = new yourObject { Name = "Test" };
     context.yourObject.Add(dpt);
     context.SaveChanges(); 
}

you are missing to add object in the context




回答3:


In .Net 4.5 I get this error when I remove ToList():

Data binding to a store query is not supported.

Instead populate a DbSet with data, for example by calling Load on the DbSet, and then bind to local data.



来源:https://stackoverflow.com/questions/11790575/entity-framework-insert-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!