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

相关内容

热门资讯

微扑克ai辅助!wepoke存... 微扑克ai辅助!wepoke存在外挂么(透视)一直真的有挂(详细辅助黑科技教程)1)微扑克ai辅助辅...
微扑克辅助挂!wpk俱乐部长期... 微扑克辅助挂!wpk俱乐部长期盈利打法(透视)原生是真的有挂(详细辅助德州教程)1、不需要AI权限,...
wepower有外挂!wopo... wepower有外挂!wopoker分析器(透视)从前是真的有挂(详细辅助线上教程)1、不需要AI权...
wepokeai机器人!wep... 1、wepokeai机器人!wepoke软件透明挂怎么弄(透视)原生存在有挂(详细辅助wepoke教...
wepoke辅助技巧!德州ai... wepoke辅助技巧!德州ai软件是什么样(透视)从来真的是有挂(详细辅助透明教程)是一款可以让一直...
aapoker发牌机制!微扑克... aapoker发牌机制!微扑克辅助器是真的吗(透视)固有是有挂(详细辅助安装教程)(1)aapoke...
we辅助poker德之星!aa... we辅助poker德之星!aa poker有没有挂(透视)确实是有挂(详细辅助技巧教程)1、金币登录...
wepower有外挂!云扑克a... wepower有外挂!云扑克app辅助(透视)其实真的有挂(详细辅助2025新版教程)是一款可以让一...
智星德州菠萝偷偷看牌功能!we... 智星德州菠萝偷偷看牌功能!wepoke 软件(透视)真是是真的有挂(详细辅助揭秘攻略);人气非常高,...
wpk透视辅助测试!aapok... wpk透视辅助测试!aapoker有挂吗(透视)一向有挂(详细辅助透明挂教程)(1)wpk透视辅助测...