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、...
透视黑科技!大菠萝免费辅助,w... 透视黑科技!大菠萝免费辅助,wepoker破解工具,项目教程(好像真的有挂)-哔哩哔哩1)大菠萝免费...
透视专用!wepoker私人局... 透视专用!wepoker私人局辅助器怎么用(透视)开挂辅助工具(确实存在有挂)-哔哩哔哩1、wepo...
透视有挂!wepoker透视脚... 透视有挂!wepoker透视脚本苹果版,竞技联盟透视插件,教材教程(都是真的有挂)-哔哩哔哩1、不需...
三分钟法门!越乡有辅助软件,四... 三分钟法门!越乡有辅助软件,四川途游辅助软件下载,揭秘教程(有挂技巧)-哔哩哔哩1、起透看视 四川途...
透视黑科技!线上德州的辅助器是... 透视黑科技!线上德州的辅助器是什么(透视)开挂辅助攻略(切实真的有挂)-哔哩哔哩1、玩家可以在线上德...
透视能赢!pokernow辅助... 透视能赢!pokernow辅助控制,wepoker有没有辅助,阶段教程(本来真的有挂)-哔哩哔哩1、...
九分钟窍门!乐玩游戏辅助工具,... 九分钟窍门!乐玩游戏辅助工具,新芒果监利开机贴吧,黑科技教程(有挂方法)-哔哩哔哩小薇(透视辅助)致...
透视线上!wepoker有没有... 透视线上!wepoker有没有透视方法(透视)开挂辅助方法(原来有挂)-哔哩哔哩1、进入游戏-大厅左...
九分钟策略!途游游戏辅助软件,... 九分钟策略!途游游戏辅助软件,顺欣茶楼有没有辅助,系统教程(有挂细节)-哔哩哔哩1、全新机制【顺欣茶...