简体   繁体   English

如何使用 EF Core 与孩子一起更新数据

[英]How to update data with child using EF Core

I have these two models:我有这两个模型:

public class Film
{
    public long Id { get; set; }
    [Required]
    public string Title { get; set; }
    [Required]
    public string Director { get; set; }
    public string Synopsis { get; set; }
    public int? Release { get; set; }
    [Required]
    public Genre Genre { get; set; }
}

public class Genre
{
    public long Id { get; set; }
    public string Description { get; set; }
}

And I want to be able to update a Film's Genre through a PUT method.我希望能够通过 PUT 方法更新电影的流派。 I am currently trying this, but I get the following error:我目前正在尝试此操作,但出现以下错误:

[HttpPut]
public async Task<IActionResult> UpdateFilm(Film film)
{
    var existingFilm = await _context.Films
        .Include(f => f.Genre)
        .FirstOrDefaultAsync(f => f.Id == film.Id);

    if (existingFilm == null)
    {
        return NotFound(new JsonResponse { Success = false, Message = "Impossible to update, film was not found", Data = null });
    }

    existingFilm.Title = film.Title;
    existingFilm.Synopsis = film.Synopsis;
    existingFilm.Release = film.Release;
    existingFilm.Director = film.Director;

    if (existingFilm.Genre.Id != film.Genre.Id)
    {
        existingFilm.Genre.Id = film.Genre.Id;
        existingFilm.Genre.Description = film.Genre.Description;
        //_context.Entry(existingFilm.Genre).State = EntityState.Modified;
        _context.Entry(existingFilm).CurrentValues.SetValues(film);
    }

    _context.Films.Update(existingFilm);

    try
    {
        await _context.SaveChangesAsync();
    }
    catch (Exception e)
    {
        return BadRequest(new JsonResponse { Success = false, Message = e.Message, Data = null });
    }

    return Ok(new JsonResponse { Success = true, Message = "Film updated with success", Data = film });
}

The error message is:错误信息是:

System.InvalidOperationException: The property 'Id' on entity type 'Genre' is part of a key and so cannot be modified or marked as modified. System.InvalidOperationException:实体类型“流派”上的属性“Id”是键的一部分,因此无法修改或标记为已修改。 To change the principal of an existing entity with an identifying foreign key first delete the dependent and invoke 'SaveChanges' then associate the dependent with the new principal.要使用标识外键更改现有实体的主体,首先删除依赖项并调用“SaveChanges”,然后将依赖项与新主体相关联。

Anyone able to help?任何人都可以提供帮助? Thanks a lot.非常感谢。

According to the error, its existingFilm.Genre.Id that you cannot update the id, if its not equal to the id.根据错误,它的existingFilm.Genre.Id不能更新 id,如果它不等于 id。

My suggestion would be ignore the id update, but if it is necessary:我的建议是忽略id更新,但如果有必要:

if (existingFilm.Genre.Id != film.Genre.Id)
{
    var genre = _context.Genre.FirstOrDefault(x => x.Id == film.Genre.Id);
    // Update the fields needed except the id

    existingFilm.Genre = genre;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM