使用ASP.NET Core 6 MVC更新数据库中的多个模型。

huangapple go评论72阅读模式
英文:

Updating multiple models in database using ASP.NET Core 6 MVC

问题

需要更新我的数据库中具有一对多关系的两个表格。

这是我的Course模型:

[Key]
public int Id { get; set; }

[Required]
public string Name { get; set; }

// Relationships
public virtual ICollection<MajorCourse>? MajorsCourses { get; set; }

这是我的MajorCourse模型:

[Key]
public int Id { get; set; }
public int NumberOfUnits { get; set; }
public int CourseId { get; set; }
public virtual Course? Course { get; set; }
public int MajorId { get; set; }
public virtual Major? Major { get; set; }

public virtual ICollection<UserMajorCourse>? UsersMajorsCourses { get; set; }

这是MajorCourseVM

public int NumberOfUnits { get; set; }
public int CourseId { get; set; }
public int MajorId { get; set; }
public string Name { get; set; }
public string GradeId { get; set; }

这是我的尝试:

public async Task<IActionResult> Edit(MajorCourseVM majorCourseVM)
{
    if (!ModelState.IsValid)
    {
        return View(majorCourseVM);
    }

    Course course = new Course();
    course.Name = majorCourseVM.Name;
    course.Id = majorCourseVM.CourseId;

    MajorCourse majorCourse = new MajorCourse();
    majorCourse.MajorId = majorCourseVM.MajorId;
    majorCourse.CourseId = majorCourseVM.CourseId;
    majorCourse.NumberOfUnits = majorCourseVM.NumberOfUnits;

    _context.Attach(course);
    _context.Entry(course).State = EntityState.Modified;
    _context.Attach(majorCourse);            
    _context.Entry(majorCourse).State = EntityState.Modified;

    await _context.SaveChangesAsync();

    return RedirectToAction(nameof(Index));
}

但我收到以下错误消息:

属性'Course.Id'在尝试将实体状态更改为'Modified'时具有临时值。要么明确设置一个永久值,要么确保数据库配置为为此属性生成值。

我找不到解决方案,不知道该怎么办!

英文:

I need to update two tables with a one-to-many relationship in my database.

This is my Course model:

[Key]
public int Id { get; set; }

[Required]
public string Name { get; set; }

// Relationships
public virtual ICollection&lt;MajorCourse&gt;? MajorsCourses { get; set; }

This is my MajorCourse model:

[Key]
public int Id { get; set; }
public int NumberOfUnits { get; set; }
public int CourseId { get; set; }
public virtual Course? Course { get; set; }
public int MajorId { get; set; }
public virtual Major? Major { get; set; }

public virtual ICollection&lt;UserMajorCourse&gt;? UsersMajorsCourses { get; set; }

This is MajorCourseVM:

public int NumberOfUnits { get; set; }
public int CourseId { get; set; }
public int MajorId { get; set; }
public string Name { get; set; }
public string GradeId { get; set; }

Here is my attempt:

public async Task&lt;IActionResult&gt; Edit(MajorCourseVM majorCourseVM)
{
        if (!ModelState.IsValid)
        {
            return View(majorCourseVM);
        }

        Course course = new Course();
        course.Name = majorCourseVM.Name;
        course.Id = majorCourseVM.CourseId;

        MajorCourse majorCourse = new MajorCourse();
        majorCourse.MajorId = majorCourseVM.MajorId;
        majorCourse.CourseId = majorCourseVM.CourseId;
        majorCourse.NumberOfUnits = majorCourseVM.NumberOfUnits;

        _context.Attach(course);
        _context.Entry(course).State = EntityState.Modified;
        _context.Attach(majorCourse);            
        _context.Entry(majorCourse).State = EntityState.Modified;

        await _context.SaveChangesAsync();

        return RedirectToAction(nameof(Index));
}

But I get the following error:

> The property 'Course.Id' has a temporary value while attempting to change the entity's state to 'Modified'. Either set a permanent value explicitly, or ensure that the database is configured to generate values for this property.

I couldn't find a solution and don't know what to do!

答案1

得分: 0

以下是翻译好的部分:

但我收到以下错误:

属性 'Course.Id' 在试图更改实体状态为 'Modified' 时具有临时值。要么明确设置永久值,要么确保数据库配置为为此属性生成值。

这个错误相当明显,通常在尝试添加/更新不存在的外键实体时发生异常。

最重要的是,在更新现有对象时,您应该根据现有的 Id 获取对象,然后使用它来更新当前数据。但在您分享的代码片段中,我看到您正在创建新对象,这会导致问题,因为它肯定会与您现在拥有的外键发生冲突。相反,您应该通过其 Id 传递对象以更新现有对象。

您应该按照以下方式操作:

public async Task<IActionResult> Edit(MajorCourseVM majorCourseVM)
{
    if (!ModelState.IsValid)
    {
        return View(majorCourseVM);
    }

    var dbContextCourse = _context.Course
        .Include(s => s.MajorsCourses)
        .FirstOrDefault(s => s.Id.Equals(majorCourseVM.Id));

    dbContextCourse.Name = majorCourseVM.Name;
    dbContextCourse.MajorsCourses = majorCourseVM.majorCourse;
    //同样适用于其他实体。
    //您可以在此处执行断开连接的更新操作。

    await _context.SaveChangesAsync();

    return RedirectToAction(nameof(Index));
}

**注意:**上面的示例是为了您的理解而制作的,只需根据您的情况进行必要的更改。请参考 此官方文档 以获取更多清晰信息。

希望这对您有帮助。如需进一步翻译或其他帮助,请随时提问。

英文:

> But I get the following error:
>
> The property 'Course.Id' has a temporary value while attempting to
> change the entity's state to 'Modified'. Either set a permanent value
> explicitly, or ensure that the database is configured to generate
> values for this property.

The error is pretty obvious and the exception usually happened when you try to add/update an entity with a foreign key that does not exists.

Most importantly while updating existing object you should get the object by existing Id then need to update the the current data with it. But in your shared code snippet I can see you are creating new object which causing the issue because, it will certainly encounter conflict with the fogerign key which you are having now. Instead you should pass object by its Id in order to update existing object

You should do as following:

<!-- language: c# -->
public async Task<IActionResult> Edit(MajorCourseVM majorCourseVM)
{
if (!ModelState.IsValid)
{
return View(majorCourseVM);
}

         var dbContextCourse = _context.Course 
        .Include(s =&gt; s.MajorsCourses)
        .FirstOrDefault(s =&gt; s.Id.Equals(majorCourseVM.Id));
    
        dbContextCourse.Name = majorCourseVM.Name;
        dbContextCourse.MajorsCourses = majorCourseVM.majorCourse;
        //Same goes for other entities as well.
        //You can execute a disconnected update operation here. 

        await _context.SaveChangesAsync();

        return RedirectToAction(nameof(Index));
}

Note: Above example has been made for your understanding, just made necessary changes in order to fit within your scenario.Please refer to this official document for more clarity.

huangapple
  • 本文由 发表于 2023年6月26日 22:38:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76557710.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定