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

相关内容

热门资讯

wepokeai机器人(透视)... wepokeai机器人(透视)wepoke有没有玄学(详细辅助新2025版)确实是有挂(可靠辅助德之...
wepoke模拟器(透视)we... wepoke模拟器(透视)wepoke软件透明功能实现方法(详细辅助教你教程)好像是真的有挂(科普插...
wepoke辅助德之星(透视)... wepoke辅助德之星(透视)wepooke app系统规律(详细辅助攻略方法)真是是有挂(教你有辅...
wepoke有辅助挂(透视)w... wepoke有辅助挂(透视)wepoke有辅助挂吗(详细辅助科技教程)一直是有挂(教你透视挂)1、让...
wepoke辅助有挂(透视)w... wepoke辅助有挂(透视)wepoke人有挂吗(详细辅助可靠技巧)其实有挂(了解辅助)1.wepo...
wepoke插件(透视)wep... wepoke插件(透视)wepoke软件收费是真的吗(详细辅助辅助教程)其实真的是有挂(专业模拟器)...
wepoke辅助德之星(透视)... wepoke辅助德之星(透视)wopoker辅助(详细辅助新2025教程)真是真的有挂(玩家ai机器...
we辅助poker德之星(透视... we辅助poker德之星(透视)wepoke辅助挂在哪开(详细辅助新2025版)确实是真的有挂(大神...
wepoke黑科技(透视)we... wepoke黑科技(透视)wepoke挂真的假的(详细辅助揭秘攻略)竟然存在有挂(攻略计算辅助)1、...
wepoke智能ai(透视)w... wepoke智能ai(透视)wepower让系统发好牌(详细辅助教你攻略)真是真的有挂(详细有挂)1...