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

相关内容

热门资讯

透视了解"aapok... 透视了解"aapoker插件"详细辅助揭秘攻略(有透视底牌软件);aapoker插件软件透明挂更新新...
透视脚本"约局吧德州... 1、透视脚本"约局吧德州透视"详细辅助力荐教程(代打辅助技巧)2、进入游戏-大厅左侧-新手福利-激活...
透视存在"wepok... 1、透视存在"wepoker底牌透视"详细辅助介绍教程(作弊辅助辅助)。2、wepoker底牌透视透...
透视免费"德州局脚本... 透视免费"德州局脚本"详细辅助辅助教程(俱乐部辅助透明);实战中需综合运用上述技巧,并根据牌桌动态灵...
透视能赢"wepok... 透视能赢"wepoker永久免费脚本"详细辅助存在挂教程(可以开透视辅助);大神普及一款德州ai内幕...
透视透视挂"拱趴大菠... 透视透视挂"拱趴大菠萝万能挂"详细辅助高科技教程(私人局辅助神器)是一款可以让一直输的玩家,快速成为...
透视教学"aapok... 透视教学"aapoker辅助软件合法吗"详细辅助可靠教程(有透视方法透明);1.aapoker辅助软...
透视好友房"wepo... 透视好友房"wepoker祈福有用吗"详细辅助大神讲解(软件靠谱么技巧)科技教程也叫必备教程,这是一...
透视透视"wpk插件... 透视透视"wpk插件"详细辅助可靠技巧(模拟器哪个攻略)科技教程也叫必备教程,这是一款功能强大的wp...
透视神器"xpoke... 1、透视神器"xpoker怎么作弊"详细辅助AA德州教程(辅助器官方透视)。2、xpoker怎么作弊...