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的信息,并保存到数据库中。

相关内容

热门资讯

透视普及"来玩德州破... 透视普及"来玩德州破解器"本来有辅助方法(哔哩哔哩)暗藏猫腻,小编详细说明来玩德州破解器破解器有用吗...
透视专业"hhpok... 透视专业"hhpoker免费辅助器"都是真的是有辅助插件(哔哩哔哩)1、起透看视 hhpoker免费...
透视必备"wepok... 透视必备"wepoker怎么发冤家牌"本来真的有辅助器(哔哩哔哩)1、该软件可以轻松地帮助玩家将we...
透视解迷"aapok... 您好,aapoker怎么拿好牌这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054...
透视曝光"we po... 透视曝光"we poker免费辅助器"一贯存在有辅助技巧(哔哩哔哩)we poker免费辅助器脚本下...
透视透视"wepok... 透视透视"wepoker有辅助插件吗"真是存在有辅助攻略(哔哩哔哩)一、wepoker有辅助插件吗可...
透视必备"拱趴大菠萝... 透视必备"拱趴大菠萝挂哪里"竟然是有辅助方法(哔哩哔哩)1、首先打开拱趴大菠萝挂哪里辅助器下载最新版...
透视必备"uupok... 您好,uupoker有透视吗这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】...
透视揭露"wepok... 透视揭露"wepoker代打辅助机器人"一贯有辅助教程(哔哩哔哩)1.wepoker代打辅助机器人 ...
透视解密"hhpok... 透视解密"hhpoker软件可以玩吗"原来是有辅助脚本(哔哩哔哩)透视解密"hhpoker软件可以玩...