c# - DbContext 对象在循环内不起作用

标签 c# asp.net asp.net-mvc entity-framework asp.net-mvc-5

这是我的ActionMethod,它不会将数据填充到数据库中。

private StudentDBContext db = new StudentDBContext();

public ActionResult PopulateData()
        {
            Student objStu = new Student();

            for(int i=0;i<2;i++)
            {
                objStu.ID = i+1;
                objStu.name = "something";
                db.Students.Add(objStu);
                db.SaveChanges();
            }


            return View();
        }

只有当我没有循环使用它时才会出现(如下所示)为什么会这样?

public ActionResult PopulateData()
        {
            Student objStu = new Student();

            //for(int i=0;i<2;i++)
            //{
                objStu.ID = 1;
                objStu.name = "something";
                db.Students.Add(objStu);
                db.SaveChanges();
            //}


            return View();
        }

最佳答案

您一遍又一遍地添加同一个学生。相反,在循环内创建新学生 (objStu):

public ActionResult PopulateData()
{        
    for(int i=0;i<2;i++)
    {
        Student objStu = new Student();
        objStu.ID = i+1;
        objStu.name = "something";
        db.Students.Add(objStu);
    }

    db.SaveChanges();

    return View();
}

关于c# - DbContext 对象在循环内不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24638233/

相关文章:

c# - 将 Windows 7 64 位机器上的 C# 项目转换为 Windows xp 32 位?

c# - 502 请求 azure 内的支付服务 'website'

c# - 如何更新 ListView 选中的项目?

c# - ListView 中的 Xamarin Forms 按钮命令绑定(bind)

asp.net - 在 ASP.NET MVC 中提供无扩展名的静态文件;得到 404s

c# - 如何从 SQL 中读取父子数据?

c# - 为什么我不能在封闭泛型的继承属性中使用 C# 语法,但 CLR 语法很好

ajax - 如何让 PUT 和 DELETE 动词与 IIS 上的 Web API 一起使用

c# - 使用 mvc 2010 在 SQL Server 中上传/下载 pdf 文件

asp.net-mvc - 是否可以从 URL(基于 Global.asax 路由)获取 Controller 、操作和路由值?