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

相关内容

热门资讯

透视中牌率!uupoker有透... 透视中牌率!uupoker有透视吗(透视)真是有辅助工具(证实有挂)-哔哩哔哩1、起透看视 uupo...
目前来看!wepoker公共底... 目前来看!wepoker公共底牌(透视)原来是有辅助工具(真实有挂)-哔哩哔哩wepoker公共底牌...
透视线上!wepoker透视脚... 透视线上!wepoker透视脚本苹果版(透视)本来是真的辅助神器(的确有挂)-哔哩哔哩1、完成wep...
透视有挂!pokemmo辅助器... 透视有挂!pokemmo辅助器手机版下载(透视)一贯存在有辅助工具(有挂教程)-哔哩哔哩亲,关键说明...
透视教程!hhpoker透视脚... 透视教程!hhpoker透视脚本(透视)好像存在有辅助插件(真是有挂)-哔哩哔哩1、点击下载安装,h...
透视新版!德州hhpoker是... 透视新版!德州hhpoker是真的吗(透视)总是真的有辅助神器(揭秘有挂)-哔哩哔哩一、德州hhpo...
据玩家消息!佛手在线大菠萝为什... 您好,佛手在线大菠萝为什么都输这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302...
今天上午!we-poker是什... 今天上午!we-poker是什么软件(透视)真是存在有辅助辅助器(揭秘有挂)-哔哩哔哩今天上午!we...
有消息称!we-poker辅助... 有消息称!we-poker辅助器(透视)其实是真的辅助软件(确实有挂)-哔哩哔哩1、任何we-pok...
现有关情况通报如下!wepok... 现有关情况通报如下!wepoker辅助是真的吗(透视)真是存在有辅助下载(确实有挂)-哔哩哔哩1、该...