Context.SaveChanges()没有';不起作用

本文关键字:不起作用 没有 SaveChanges Context | 更新日期: 2023-09-27 18:15:08

我有点困惑。

我有这个代码:

 using(Test_ASLEntities context = new Test_ASLEntities())
            { 
                List<Belege> kopieren_SQL_List = new List<Belege>();
                kopieren_SQL_List = (from b in context.Beleges
                                    select b).ToList();
                var kopieren_SQL = new Belege
                {
                    Plz = 1000,                   
                    Nachname = "Name",
                    Vorname = "Name",
                };
                kopieren_SQL_List.Add(kopieren_SQL);
                context.SaveChanges();
            }
            Console.ReadLine();

我不明白,为什么它不把更改保存在m数据库中?!

上下文来自.edmx数据模型实体。

有人能告诉我我在那里做错了什么吗?(我只是从我创建了很长一段时间的另一个程序中复制了大部分代码,在那里它运行得很好。这更令人困惑(

编辑:NVM,看到了我的错误。Sry:(

Context.SaveChanges()没有';不起作用

使用context.Beleges.Add(kopieren_SQL)而不是kopieren_SQL_List.Add(kopieren_SQL)

您没有将新的Belege添加到数据上下文中。

尝试context.Beleges.Add(kopieren_SQL)

因为您必须使用DbSet对象来表示新对象已添加到EF
MSDNAdd方法做

Adds the given entity to the context underlying the set in the Added state such that it will be inserted into the database when SaveChanges is called.

 var kopieren_SQL = new Belege
                {
                    Plz = 1000,                   
                    Nachname = "Name",
                    Vorname = "Name",
                };
//EF framework will add a plural S to represents an object collection 
context.Beleges.Add(kopieren_SQL); 
//here  commit your changes to the DB 
context.SaveChanges();