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

相关内容

热门资讯

解迷透视!wpk私人局辅助是真... 解迷透视!wpk私人局辅助是真的吗!盘点十款辅助软件(讲解有挂)-哔哩哔哩1、wpk私人局辅助是真的...
推荐透视!德州真人透视脚本!热... 推荐透视!德州真人透视脚本!热点讨论辅助攻略(有挂秘籍)-哔哩哔哩1、上手简单,内置详细流程视频教学...
专业透视!we poker辅助... 专业透视!we poker辅助器!玩家必备教程辅助脚本(有挂头条)-哔哩哔哩1、每一步都需要思考,不...
解迷透视!德普之星app安卓版... 解迷透视!德普之星app安卓版破解版!玩家科普辅助攻略(发现有挂)-哔哩哔哩在进入德普之星app安卓...
科普透视!wepoker手机插... 科普透视!wepoker手机插件!传递经验辅助方法(果真有挂)-哔哩哔哩1、进入游戏-大厅左侧-新手...
解密透视!we poker辅助... 解密透视!we poker辅助器下载!交流学习经验辅助技巧(有挂透视)-哔哩哔哩1、进入到we po...
详情透视!红龙poker辅助器... 详情透视!红龙poker辅助器免费观看!推荐攻略辅助技巧(有挂解密)-哔哩哔哩1、红龙poker辅助...
有挂透视!wepoker好友助... 有挂透视!wepoker好友助力码!推荐十款辅助软件(确实有挂)-哔哩哔哩运wepoker好友助力码...
开挂透视!wepoker透视脚... 开挂透视!wepoker透视脚本免费使用视频!推荐攻略辅助软件(有挂工具)-哔哩哔哩;1.wepok...
分享透视!hhpoker德州透... 分享透视!hhpoker德州透视!每日必看辅助教程(有挂实锤)-哔哩哔哩1、hhpoker德州透视免...