简体   繁体   中英

Entity Framework not updating changes 6

Asp.net MVC not updating data I have two tables relationship 1:M user to many Roles When I modify the user it saves data, but it is not updating Role

if (role != "Select Role")
{
   obj.Roles.Add(_context.Roles.FirstOrDefault(c => c.Name == role)); 
}
obj.UpdatedBy = System.Configuration.ConfigurationManager.AppSettings["UserDomain"] + Environment.UserName;
obj.UpdatedByDate = DateTime.Today;
_context.Entry(obj).State = obj.Id == 0 ? EntityState.Added : EntityState.Modified;
_context.SaveChanges();
return true;

Let me modifiy the code ------ this is the code two model User and Role

public bool Update(User obj,string role)
{
    try
    {
          if (role != "Select Role")
        {
        obj.Roles.Add(_context.Roles.FirstOrDefault(c => c.Name == role));
        }
        obj.UpdatedBy = System.Configuration.ConfigurationManager.AppSettings["UserDomain"] + Environment.UserName;
        obj.UpdatedByDate = DateTime.Today;
        _context.Entry(obj).State = obj.Id == 0 ? EntityState.Added : EntityState.Modified;
        _context.SaveChanges();
        return true;
    }
    catch (Exception e)
    {


        return false;
    }
}

Replace the following line:

obj.Roles.Add(_context.Roles.FirstOrDefault(c => c.Name == role));

with the folowing:

var Role = _context.Roles.FirstOrDefault(c => c.Name == role);
Role.User = obj;
_context.Entry(Role).State = EntityState.Modified;

This way it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM