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

相关内容

热门资讯

透视关于!福建大菠萝万能辅助器... 透视关于!福建大菠萝万能辅助器(透视)pokermaster破解版,教程策略(有挂攻略)-哔哩哔哩1...
透视解谜!aapoker透视插... 透视解谜!aapoker透视插件(透视)约局吧德州透视,教程诀窍(有挂解惑)-哔哩哔哩约局吧德州透视...
透视有挂!wepoker辅助器... 透视有挂!wepoker辅助器官方(透视)pokemmo手机辅助软件,教程方针(有挂解惑)-哔哩哔哩...
透视普及!德州hhpoker脚... 透视普及!德州hhpoker脚本(透视)约局吧德州有挂吗,教程秘籍(有挂技术)-哔哩哔哩1.约局吧德...
透视专业!佛手大菠萝辅助(透视... 透视专业!佛手大菠萝辅助(透视)we poker游戏下,教程积累(有挂讲解)-哔哩哔哩1、佛手大菠萝...
透视解密!xpoker辅助助手... 透视解密!xpoker辅助助手(透视)wepoker辅助器如何使用,教程手册(有挂猫腻)-哔哩哔哩1...
透视开挂!wpk辅助是什么(透... 透视开挂!wpk辅助是什么(透视)德扑圈透视挂,教程要领(确实有挂)-哔哩哔哩所有人都在同一条线上,...
透视专业!sohoo poke... 透视专业!sohoo poker辅助器(透视)wejoker黑侠辅助器,教程教程书(的确有挂)-哔哩...
透视辅助!aapoker公共底... 透视辅助!aapoker公共底牌(透视)wepoker透视脚本免费app,教程诀窍(有挂技巧)-哔哩...
透视透视!werplan透视挂... 透视透视!werplan透视挂(透视)wepoker透视脚本下载,教程妙招(发现有挂)-哔哩哔哩1、...