gpt4 book ai didi

c# - SaveChanges 返回 0 并且根本不保存数据

转载 作者:太空宇宙 更新时间:2023-11-03 22:44:06 25 4
gpt4 key购买 nike

Entity Framework 的 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();
}
}
}

最佳答案

我相信您尝试做的加载现有用户,如果存在,则更新它。

试试这段代码:

[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() 调用应该 为您更新现有用户

关于c# - SaveChanges 返回 0 并且根本不保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50784134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com