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

相关内容

热门资讯

让我来分享经验!hhpoker... 让我来分享经验!hhpoker是真的吗,如何下载wpk透视版,其实是有挂(存在有挂)1、完成有辅助插...
我来教教大家!xpoker辅助... 我来教教大家!xpoker辅助器,aapoker插件下载,总是真的有挂(有挂透视)1、全新机制【ai...
总算了解!wpk辅助器,soh... 总算了解!wpk辅助器,sohoo poker辅助,切实真的有挂(有挂方式)1、起透看视 辅助软件价...
指导大家!来玩app 德州 辅... 指导大家!来玩app 德州 辅助,wepoker好友助力码,都是是真的有挂(有挂分析)1、这是跨平台...
玩家必看攻略!wepoker轻... 玩家必看攻略!wepoker轻量版透视系统,wepoker高级辅助,真是存在有挂(有挂实锤)辅助器是...
一分钟快速了解!wepoker... 一分钟快速了解!wepoker透视最简单三个步骤,购买的wpk辅助在哪里下载,其实有挂(有挂教学)1...
玩家爆料!wepoker辅助器... 玩家爆料!wepoker辅助器安装包,wepoker辅助器安装包,总是是真的有挂(有挂规律)1、we...
最新技巧!hhpoker有后台... 最新技巧!hhpoker有后台操作吗,pokemmo手机版脚本,竟然存在有挂(有挂教学)1、透视辅助...
带你了解!德普之星有辅助软件吗... 带你了解!德普之星有辅助软件吗,红龙poker有辅助吗,竟然真的有挂(详细教程)1、进入游戏-大厅左...
分享给玩家!wejoker内置... 分享给玩家!wejoker内置辅助,约局吧德州透视,果然存在有挂(今日头条)1)有没有挂:进一步探索...