Reputation: 8932
I have written the following code to Add If does not exist
or Update if exist
student record in the table.
I am using Entity Framework 6.1.1
version.
It works for me but i feel it is very basic level code. Is there any better way i can re-write it please?
Code:
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();
}
}
}
Upvotes: 2
Views: 239
Reputation: 20393
There is AddOrUpdate
method at namespace System.Data.Entity.Migrations.
public void AddOrUpdate(Student student)
{
using (var context = new DBContext())
{
context.Student.AddOrUpdate(student);
context.SaveChanges();
}
}
Upvotes: 2