【问题标题】:How to add/update many to many relations with one end of entity in EF core如何在 EF 核心中添加/更新与实体一端的多对多关系
【发布时间】:2020-01-11 15:17:11
【问题描述】:

我们访问了很多关于 EF Core 多对多更新的链接,但无法为我们的问题找到一个具体的答案并澄清我们的理解。

场景: 我们希望一次性添加/更新一个实体及其相关的多对多关系,例如 (dbset.Add() 或 dbset.Update())

我们正在尝试以下操作,只能添加/更新父实体,而不是多对多关系列表。你能帮助我们知道我们错在哪里吗?可以做什么?

当前模型结构:


        public class Teacher
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity), Required]
        public long Id { get; set; }
        public string Name { get; set; }
        public List<TeacherDuty> TeacherDuties { get; set; }
    }
    public class Duty
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity), Required]
        public long Id { get; set; }
        public string Description { get; set; }
        public List<TeacherDuty> TeacherDuties { get; set; }
    }
    public class TeacherDuty
    {
        public long TeacherId { get; set; }
        public Teacher Teacher { get; set; }

        public long DutyId { get; set; }
        public Duty Duty { get; set; }
    }

我们正在尝试使用以下方法添加/更新:

public async Task<Teacher> AddTeacher(Teacher pTeacher)
{
    try
    {
        return await _teacher.AddAsync(pTeacher);
    }
    catch (Exception ex) { throw ex; }
}

public async Task<Teacher> UpdateTeacher(Teacher pTeacher)
{
    try
    {
        return await _teacher.Update(pTeacher);
    }
    catch (Exception ex) { throw ex; }
}

如果可能,请指出我们对概念和解决方案的误解。 谢谢。

【问题讨论】:

  • 这并没有提供足够的信息来了解为什么它只更新父对象。您能否提供一个您正在添加的教师样本以及任务的调用方式
  • 以下是更新时教师的样本.. ` { "Name": "Kasperov", "Id": 1, "TeacherDuties": [{ "TeacherId" : 1, "DutyId" : 3 }] } ` - 这是我们想要从 1 中删除 DutyId 并添加 3 的时候

标签: c# many-to-many asp.net-core-webapi crud ef-core-2.2


【解决方案1】:

我创建了一个演示来添加和编辑老师。(_context 是数据库上下文)

添加老师:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Teacher teacher)
    {
        //get your desired dutyId with your own logic
        var SelectedDutyIds = new int[] { 1 };
        var teacherDuties = new List<TeacherDuty>();

        if (ModelState.IsValid)
        {
            _context.Add(teacher);
            await _context.SaveChangesAsync();


            foreach (var id in SelectedDutyIds)
            {
                var item = new TeacherDuty()
                {
                    TeacherId = teacher.Id,
                    DutyId = id,
                };
                teacherDuties.Add(item);
            }
            _context.AddRange(teacherDuties);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(teacher);
    }

编辑老师:先删除老师现有​​的TeacherDuties,再添加新的。

 [HttpPost]
 [ValidateAntiForgeryToken]
 public async Task<IActionResult> Edit(long id, Teacher teacher)
    {
        if (id != teacher.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
               //your new dutyIds
                var newSelectedDutyIds = new int[] { 3 };
                var teacherDuties = new List<TeacherDuty>();


                var tdList = await _context.TeacherDuties.Where(td => td.TeacherId == teacher.Id).ToListAsync() ;
                _context.RemoveRange(tdList);

                foreach (var newid in newSelectedDutyIds)
                {
                    var item = new TeacherDuty()
                    {
                        TeacherId = teacher.Id,
                        DutyId = newid,
                    };
                    teacherDuties.Add(item);
                }
                _context.AddRange(teacherDuties);
                _context.Update(teacher);

                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TeacherExists(teacher.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }
        return View(teacher);
    }

参考Entity framework core update many to many

【讨论】:

    猜你喜欢
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    相关资源
    最近更新 更多