ASP .NET MVC - 无法更新一对一的数据
创始人
2024-11-11 15:00:16
0次

在ASP .NET MVC中,有时候在更新一对一关系的数据时会遇到问题。下面是一个解决该问题的示例代码。

假设我们有两个实体类:User和Profile,它们之间是一对一的关系。

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Profile Profile { get; set; }
}

public class Profile
{
    public int Id { get; set; }
    public string Address { get; set; }
    public User User { get; set; }
}

在Controller中,我们可以使用EF Core来更新一对一关系的数据。

public class UserController : Controller
{
    private readonly ApplicationDbContext _context;

    public UserController(ApplicationDbContext context)
    {
        _context = context;
    }

    public IActionResult Edit(int id)
    {
        // 获取要编辑的用户
        User user = _context.Users.Include(u => u.Profile).FirstOrDefault(u => u.Id == id);

        return View(user);
    }

    [HttpPost]
    public IActionResult Edit(User user)
    {
        if (ModelState.IsValid)
        {
            // 更新用户信息
            _context.Users.Update(user);

            // 更新用户的Profile信息
            _context.Profiles.Update(user.Profile);

            _context.SaveChanges();

            return RedirectToAction("Index");
        }

        return View(user);
    }
}

在Edit视图中,我们可以使用表单来编辑用户和Profile的信息。

@model User

这样,当用户提交编辑表单时,会更新User和Profile的信息,并保存到数据库中。

相关内容

热门资讯

2027版透视器!博乐兴安盟麻... 2027版透视器!博乐兴安盟麻将透视器多功能AI攻略,博乐兴安盟麻将一直真的是有透视器攻略博乐兴安盟...
2027版外挂!川滇互娱麻将外... 2027版外挂!川滇互娱麻将外挂多功能AI插件,川滇互娱麻将原来真的是有外挂插件1、首先打开川滇互娱...
2027版辅助器!胡桃娱乐辅助... 2027版辅助器!胡桃娱乐辅助器多功能AI工具,胡桃娱乐果然是真的有辅助器工具2027版辅助器!胡桃...
2027版辅助!玉兔互娱辅助多... 2027版辅助!玉兔互娱辅助多功能AI脚本,玉兔互娱一贯存在有辅助脚本1、用户打开应用后不用登录就可...
2027版辅助器!乐乐阜阳麻将... 2027版辅助器!乐乐阜阳麻将辅助器多功能AI软件,乐乐阜阳麻将一贯存在有辅助器软件1、在乐乐阜阳麻...
2027版透视器!呼包鄂麻将胡... 2027版透视器!呼包鄂麻将胡一把透视器多功能AI工具,呼包鄂麻将胡一把竟然真的有透视器工具1、每一...
2027版透视挂!17麻将众娱... 2027版透视挂!17麻将众娱透视挂多功能AI攻略,17麻将众娱总是是真的有透视挂攻略1、17麻将众...
2027版透视挂!天天飞小鸡透... 2027版透视挂!天天飞小鸡透视挂多功能AI方法,天天飞小鸡原来是真的有透视挂方法在进入天天飞小鸡软...
2027版透视挂!中至二人透视... 2027版透视挂!中至二人透视挂多功能AI脚本,中至二人本来真的是有透视挂脚本亲,关键说明,中至二人...
2027版外挂!掌中乐游戏中心... 2027版外挂!掌中乐游戏中心外挂多功能AI攻略,掌中乐游戏中心果然有外挂攻略1、掌中乐游戏中心辅助...