gpt4 book ai didi

c# - 当对象从另一个类返回时无法保存 Entity Framework 中的更改

转载 作者:太空宇宙 更新时间:2023-11-03 21:02:42 25 4
gpt4 key购买 nike

我正在开发从数据库更新记录的简单 MVC 应用程序。我已经使用 BAL 和 Controller 来获取记录和更新,如下所示

Student.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.DAL
{
public class Student
{
DemoDatabaseEntities db = new DemoDatabaseEntities();
public Student_Mast getStudentByID()
{
Student_Mast student = db.Student_Mast.Where(i => i.StudID == 1).FirstOrDefault();
return student;
}
}
}

StudentController.cs

public class UpdateController : Controller
{
DemoDatabaseEntities db = new DemoDatabaseEntities();
Student _bal = new Student();
/ GET: Update
public ActionResult Index()
{
Student_Mast model = new Student_Mast();
model = _bal.getStudentByID();
model.First_Name = "Hardik";
model.Last_Name = "Gondalia";
db.SaveChanges();
return View();
}
}

但是 db.savechanges() 并没有更新记录。
如果我像下面这样更新记录,而不是这个,它会起作用
StudentController.cs

public class UpdateController : Controller
{
DemoDatabaseEntities db = new DemoDatabaseEntities();
Student _bal = new Student();
/ GET: Update
public ActionResult Index()
{
Student_Mast model = new Student_Mast();
model = db.Student_Mast.Where(i => i.StudID == 1).FirstOrDefault();
model.First_Name = "Hardik";
model.Last_Name = "Gondalia";
db.SaveChanges();
return View();
}
}

最佳答案

由于您正在从 DbContext 的不同实例中检索记录,因此无法保存它。解决方案是向您的 Student 类添加一个构造函数,该类采用 DbContext 实例并将其保存到您拥有的变量中。

public class Student
{
private DemoDatabaseEntities db = null;

public Student(DemoDatabaseEntities dbContext){
{
this.db = dbContext;
}

public Student_Mast getStudentByID()
{
Student_Mast student = db.Student_Mast.Where(i => i.StudID == 1).FirstOrDefault();
return student;
}
}

关于c# - 当对象从另一个类返回时无法保存 Entity Framework 中的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43740664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com