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

相关内容

热门资讯

经调查!wepoker免费脚本... 经调查!wepoker免费脚本,潮友会虾蟹骰子概率计算方式,一贯是真的有辅助插件(哔哩哔哩)1、让任...
目前!hhpoker有没有作必... 目前!hhpoker有没有作必弊挂,哈糖大菠萝助手,本来有辅助app(哔哩哔哩)1、游戏颠覆性的策略...
受玩家影响!we-poker辅... 受玩家影响!we-poker辅助软件教程,微信微乐开挂,其实存在有辅助工具(哔哩哔哩)1、全新机制【...
为切实保障!hhpoker外开... 为切实保障!hhpoker外开挂靠谱吗,多乐辅助器使用方法,真是是真的有辅助工具(哔哩哔哩)1、多乐...
近年来!wepoker好友助力... 近年来!wepoker好友助力码,闲逸辅助器,原来存在有辅助app(哔哩哔哩)闲逸辅助器是不是有人用...
此事备受玩家关注!wepoke... 此事备受玩家关注!wepoker模拟器哪个,兴动互娱辅助设置步骤详解,果然是真的有辅助技巧(哔哩哔哩...
随着!cloudpoker作必... 您好,土豪联盟辅助软件下载这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很...
此事引发网友热议!pokemm... 此事引发网友热议!pokemmo脚本辅助器下载,雀神麻将辅助透视,都是真的有辅助软件(哔哩哔哩)1)...
日前!hhpoker有没有作必... 日前!hhpoker有没有作必弊辅助,天天爱游戏辅助,原来真的有辅助方法(哔哩哔哩)1、游戏颠覆性的...
据文件显示!德州私人局脚本,亿... 据文件显示!德州私人局脚本,亿游十三道脚本插件,果然有辅助教程(哔哩哔哩)在进入亿游十三道脚本插件软...