我对实体框架的SaveChanges()
方法有一个奇怪的问题。问题是它返回0并且根本不更新表数据。问题可能是什么?有任何想法吗?我必须更新现有用户数据
[HttpPost]
[Authorize(Roles = "User")]
public ActionResult Settings(User _users)
{
using (MydbEntities db = new MydbEntities())
{
var u = new User();
string _Email = User.Identity.GetUserId().ToString();
if(db.Users.Any(x=>x.Email == _Email))
{
u.BusinessName = _users.BusinessName;
u.Address = _users.Address;
u.VatNumber = _users.VatNumber;
u.PhoneNumber = _users.PhoneNumber;
u.IsBusinessUser = _users.IsBusinessUser;
var foo = db.SaveChanges();
}
}
}
答案 0 :(得分:3)
我相信您尝试做的内容加载现有用户,如果存在,则更新它。
试试这段代码:
[HttpPost]
[Authorize(Roles = "User")]
public ActionResult Settings(User _users)
{
using (MydbEntities db = new MydbEntities())
{
string _Email = User.Identity.GetUserId().ToString();
// try to find the existing user in the database
User existing = db.Users.FirstOrDefault(x => x.Email == _Email);
if(existing != null)
{
// if you *DID* find a user - then update its properties
existing.BusinessName = _users.BusinessName;
existing.Address = _users.Address;
existing.VatNumber = _users.VatNumber;
existing.PhoneNumber = _users.PhoneNumber;
existing.IsBusinessUser = _users.IsBusinessUser;
var foo = db.SaveChanges();
}
}
}
首先,您加载现有用户,如果您找到了,则更新其属性,现在SaveChanges()
调用 为您更新现有用户