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、辅...
透视阶段!wepoker透视破... 透视阶段!wepoker透视破解版(HHpoker机器人)真是真的是有辅助软件(哔哩哔哩)1、操作简...
透视策略!aapoker怎么选... 透视策略!aapoker怎么选牌(WePoKer脚本)原来是真的有辅助软件(哔哩哔哩)1、aapok...
出乎意料的是!微乐小程序黑科技... 出乎意料的是!微乐小程序黑科技免费,微信小程序微乐为什么老输(透视)一贯是真的辅助app(哔哩哔哩)...
复盘辅助挂!微信微乐游戏辅助脚... 复盘辅助挂!微信微乐游戏辅助脚本,微乐江西小程序辅助器免费(透视)真是存在有辅助技巧(哔哩哔哩)1、...
透视秘籍!wepoker轻量版... 透视秘籍!wepoker轻量版透视系统(WePoKer透视脚本)其实真的是有辅助攻略(哔哩哔哩)1、...
值得注意的是!微乐小程序免费黑... 值得注意的是!微乐小程序免费黑科技,微信小程序微乐辅助器免费版v2.0免费(透视)切实是有辅助攻略(...
透视窍门!拱趴大菠萝万能挂(A... 透视窍门!拱趴大菠萝万能挂(AApoker下载)一贯真的是有辅助神器(哔哩哔哩)拱趴大菠萝万能挂是不...
透视诀窍!hhpoker有透视... 您好,hhpoker有透视功能吗这款游戏可以开挂的,确实是有挂的,需要了解加去威信【13670430...
透视教学!微乐小程序黑科技免费... 透视教学!微乐小程序黑科技免费,微乐自建房黑科技工具怎么找(透视)果然存在有辅助方法(哔哩哔哩)运辅...