我已将以下代码写入表中的如果不存在则添加
或如果存在则更新
学生记录。
我使用的是 Entity Framework 6.1.1
版本。
它对我有用,但我觉得这是非常基础的代码。 请问有什么更好的方法可以重写吗?
代码:
public void Update(Student student)
{
Student student = _context.Student.Find(studentId);
Student orignal = new Student { Id = student.Id, RollNumber = student.RollNumber, StudentType = student.StudentType, Class = student.Class};
using (var context = new DBContext())
{
if (student != null)
{
context.Entry(orignal).State = EntityState.Modified;
context.SaveChanges();
}
else {
context.Student.Add(orignal);
context.SaveChanges();
}
}
}
最佳答案
命名空间 System.Data.Entity.Migrations 中有 AddOrUpdate
方法。
public void AddOrUpdate(Student student)
{
using (var context = new DBContext())
{
context.Student.AddOrUpdate(student);
context.SaveChanges();
}
}
关于c# - EF 6 - 在表编码模式中添加/更新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31668279/