【问题标题】:Context.SaveChanges() doesn't workContext.SaveChanges() 不起作用
【发布时间】:2017-12-15 12:55:02
【问题描述】:

我有点困惑。

我有这个代码:

 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,看到我的错误。对不起:(

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      试试context.Beleges.Add(kopieren_SQL)

      【讨论】:

        【解决方案3】:

        因为您必须使用DbSet 对象来表示新对象已添加到EF
        MSDN Add 方法的作用

        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();  
        

        【讨论】:

          猜你喜欢
          • 2015-01-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多