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!wepokerp... 透视智能ai!wepokerplus辅助(透视)辅助(总是是有挂);在进入wepokerplus辅助...
透视工具!德普之星app安卓版... 透视工具!德普之星app安卓版破解版(透视)透视辅助插件(切实有挂);1、上手简单,内置详细流程视频...
透视教学!wepoker透视辅... 透视教学!wepoker透视辅助下载(透视)俱乐部辅助(一直是有挂)所有人都在同一条线上,像星星一样...
透视教学!德普之星透视辅助插件... 透视教学!德普之星透视辅助插件(透视)透视(原来有挂)1、德普之星透视辅助插件系统规律教程、德普之星...
透视教学!wepoker破解器... 透视教学!wepoker破解器有用吗(透视)透视脚本免费下载(都是是真的有挂)1、全新机制【wepo...
透视黑科技!德普之星透视辅助软... 透视黑科技!德普之星透视辅助软件激活码(透视)透视辅助插件(好像是真的有挂)德普之星透视辅助软件激活...
辅助透视!wepoker线上大... 辅助透视!wepoker线上大神(透视)辅助软件价格(一直是真的有挂);1、操作简单,无需注册,只需...
透视黑科技!德扑圈透视挂(透视... 透视黑科技!德扑圈透视挂(透视)透视辅助软件激活码(好像真的有挂)1、这是跨平台的德扑圈透视挂黑科技...
透视有挂!wepoker透视a... 透视有挂!wepoker透视app下载(透视)私局辅助(真是有挂);小薇(透视辅助)致您一封信;亲爱...
透视真的!德普之星私人局辅助器... 透视真的!德普之星私人局辅助器(透视)辅助软件(都是是有挂);1、德普之星私人局辅助器系统规律教程、...