我是 .NetCore 和 Blazor 的新手。我正在嘗試對一部新動漫進行 POST,但我總是收到錯誤“需要型別欄位”。我已經添加genreId到 JSON 物件,但仍然是同樣的錯誤 -> 錯誤截圖
這是一對多的關系,一種動物只能有一種型別,而一種型別可以有很多敵人。
我不知道它是否有用,但這里是我在資料庫中的兩個表的螢屏截圖 ->動漫表和流派選項卡
這是我的模型:
動漫模型
public class Anime
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public string CoverImage { get; set; } = string.Empty;
public string Author { get; set; } = string.Empty;
public Genre Genre { get; set; }
public string Studio { get; set; } = string.Empty;
public DateTime? ReleaseDate { get; set; }
public DateTime? EndDate { get; set; }
}
流派模型
public class Genre
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
[JsonIgnore]
public List<Anime> Animes { get; set; }
}
我將新動漫添加到 DB 的 AnimeService
public async Task<ServiceResponse<List<Anime>>> AddAnime(Anime NewAnime)
{
ServiceResponse<List<Anime>> serviceResponse = new ServiceResponse<List<Anime>>();
_dataContext.Animes.Add(NewAnime);
await _dataContext.SaveChangesAsync();
var animes = await _dataContext.Animes
.Include(a => a.Genre)
.ToListAsync();
if (animes == null)
{
serviceResponse.Success = false;
serviceResponse.Message = "Animes could be found!";
}
serviceResponse.Data = animes;
return serviceResponse;
}
動漫控制器
[HttpPost]
[Route("AddAnime")]
public async Task<ActionResult<ServiceResponse<List<Anime>>>> AddAnime(Anime NewAnime)
{
return Ok(await _animeService.AddAnime(NewAnime));
}
uj5u.com熱心網友回復:
正如我們在 Discord 上討論的那樣:
您正在使用 .NET 6 并啟用可空值。
由于動漫在分配流派之前就可以存在,因此我會像這樣配置表:
public class Anime
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public string CoverImage { get; set; } = string.Empty;
public string Author { get; set; } = string.Empty;
public int? GenreId { get; set; }
[ForeignKey(nameof(GenreId))]
public Genre? Genre { get; set; }
public string Studio { get; set; } = string.Empty;
public DateTime? ReleaseDate { get; set; }
public DateTime? EndDate { get; set; }
}
public class Genre
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
[JsonIgnore]
[InverseProperty(nameof(Anime.Genre))]
public List<Anime> Animes { get; set; }
}
uj5u.com熱心網友回復:
似乎您的 Anime 實體不是 Genre 物件,但在您的 db 背景關系中需要它
如果您認為 Genre 是可選的,則必須將導航屬性 GenreId 添加為可為空
public class Anime
{
public int Id { get; set; }
... another properties
public int? GenreId { get; set; }
public virtual Genre Genre { get; set; }
}
在此之后,您將不得不進行新的資料庫遷移
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/390683.html
