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

相关内容

热门资讯

透视规律"poker... 您好,pokermaster破解版这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302...
透视玄学"wepok... 透视玄学"wepoker辅助工具"详细辅助揭秘教程(一贯真的是有挂)是一款可以让一直输的玩家,快速成...
透视透视"约局吧德州... 透视透视"约局吧德州透视"详细辅助大神讲解(一贯真的有挂)是一款可以让一直输的玩家,快速成为一个“必...
透视黑科技"德普之星... 您好,德普之星怎么设置埋牌这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩...
透视系统"红龙pok... 透视系统"红龙poker辅助工具"详细辅助靠谱教程(从前真的是有挂);玩家必备必赢加哟《136704...
透视好友房"we-p... 透视好友房"we-poker有人玩吗"详细辅助曝光教程(真是存在有挂);支持多人共享记分板与复盘,通...
透视科技"hhpok... 透视科技"hhpoker软件靠谱吗"详细辅助攻略教程(确实真的是有挂)准备好在hhpoker软件靠谱...
透视挂"hhpoke... 1、透视挂"hhpoker德州机器人"详细辅助AA德州教程(总是真的有挂)2、进入游戏-大厅左侧-新...
透视模拟器"wejo... 透视模拟器"wejoker辅助软件"详细辅助插件教程(真是有挂);最新版2024是一款经典耐玩的益智...
透视辅助"wepok... 透视辅助"wepoker透视脚本安卓"详细辅助总结教程(原本是真的有挂)是一款可以让一直输的玩家,快...