Facing an issue with Add or Update scenario

时间:2016-04-25 09:36:39

标签: c# entity-framework linq

I am trying write LINQ to Add or Update but for me EntityState.Modified is not working.

Have a look at my code and let me know if you see any error. Only new record insert works but Update does not work. I am using EF 6.0.

dbContext _context = new dbContext();            
string userName = //getting this value from somewhere else;
string userRoleNo = //getting this value from somewhere else;
Student student = new Student 
{
    userName = userName, 
    userRoleNo = userRoleNo, 
    Date = DateTime.Now 
};
bool exist = _context.Students.Any(x => x.UserId == new Guid(userId));
if (exist)
    _context.Entry(Student).State = EntityState.Modified;               
else
    _context.Students.Add(student);

_context.SaveChanges(); 

3 个答案:

答案 0 :(得分:0)

我想它应该是

db.Entry(student).State = EntityState.Modified

而不是

db.Entry(Student).State = EntityState.Modified

答案 1 :(得分:0)

只有在新学生的情况下才能添加。如果没有,EF将为您跟踪更改。这样您就可以离开跟踪并附加到EF。

dbContext _context = new dbContext();     
var student = _context.Students.FirstOrDefault(x => x.UserId == new Guid(userId)); // Get the existing student.
bool exists = true;
if(student == null){
    student = new Student();
    exists = false;
}

string userName = //getting this value from somewhere else;
string userRoleNo = //getting this value from somewhere else;
student.userName = userName; // Do you really want to reset this?
student.userRoleNo = userRoleNo;
student.Date = DateTime.Now:

if(!exists){
    _context.Students.Add(student);
}
_context.SaveChanges(); 

只有在您不从上下文中提取项目时才需要附加和EntityState.Modified。但在这种情况下,它将取代项目。

答案 2 :(得分:0)

正确的方法是

using(_context = new dbContext()){    //This will dispose the context           
string userName = //getting this value from somewhere else;
string userRoleNo = //getting this value from somewhere else;
Student student = _context.Students.FirstOrDefault(x => x.UserId == new Guid(userId));


if (student != null)
 {
   student.userName = userName; 
   student.userRoleNo = userRoleNo; 
   student.Date = DateTime.Now ;
   _context.Entry(student).State = EntityState.Modified;     
 }          
 else
 {
      student = new Student () {
       userName = userName, 
       userRoleNo = userRoleNo, 
       Date = DateTime.Now 
    };
  _context.Students.Add(student);
}
_context.SaveChanges();
};