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

相关内容

热门资讯

外挂窍要!德普之星透视辅助软件... 外挂窍要!德普之星透视辅助软件激活码,约局吧德州真的存在透视吗-真是一直总是有辅助教程(哔哩哔哩)1...
外挂模块!newpoker脚本... 外挂模块!newpoker脚本,xpoker辅助器-原来一直总是有辅助教程(哔哩哔哩)xpoker辅...
外挂指引!德普之星透视辅助软件... 外挂指引!德普之星透视辅助软件下载,智星菠萝有挂吗-本来一直总是有辅助工具(哔哩哔哩)1、用户打开应...
外挂攻略!拱趴大菠萝机器人,德... 外挂攻略!拱趴大菠萝机器人,德州圈脚本-切实真的是有辅助脚本(哔哩哔哩)拱趴大菠萝机器人破解侠是真的...
外挂手段!哈糖大菠萝怎么挂,德... 外挂手段!哈糖大菠萝怎么挂,德州局透视-总是真的是有辅助脚本(哔哩哔哩)1、起透看视 哈糖大菠萝怎么...
外挂指南书!impoker辅助... 外挂指南书!impoker辅助,sohoo开挂辅助-原来真的有辅助教程(哔哩哔哩)1、sohoo开挂...
外挂办法!约局吧作必弊脚本,a... 外挂办法!约局吧作必弊脚本,agpoker辅助-一直真的有辅助神器(哔哩哔哩)1、约局吧作必弊脚本辅...
外挂指南!线上德州的辅助器是什... 外挂指南!线上德州的辅助器是什么,佛手大菠萝13道挂哪里-确实是真的有辅助工具(哔哩哔哩)1、上手简...
外挂法子!德普之星的辅助工具介... 外挂法子!德普之星的辅助工具介绍,德普之星透视-切实存在有辅助方法(哔哩哔哩)1、打开软件启动之后找...
外挂烘培!newpoker怎么... 外挂烘培!newpoker怎么安装脚本,sohoopoker辅助-确实真的是有辅助插件(哔哩哔哩)1...