简体   繁体   English

实体框架未更新更改6

[英]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 Asp.net MVC不更新数据我有两个表的关系1:M用户与许多角色修改用户时,它保存数据,但不更新角色

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 让我修改代码------这是代码两个模型User和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. 这样,它应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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