我正在学习 Webapi,所以我尝试构建一个连接到 SQL 服务器的简单 Api,当我添加新的电影数据时,我收到此错误
Microsoft.EntityFrameworkCore.DbUpdateException:保存实体更改时发生错误。有关详细信息,请参阅内部异常。 ---> Microsoft.Data.SqlClient.SqlException (0x80131904):INSERT 语句与 FOREIGN KEY 约束“FK_Movies_SuperHeroes_HeroId”冲突。冲突发生在数据库“SupersDb”、表“dbo.SuperHeroes”、列“HeroId”中。
我有两个型号:
超级英雄模型:
namespace SuperHeroesApi.Models
{
public class SuperHero
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int HeroId { get; set; }
[Required]
[MaxLength(100)]
public string Name { get; set; }
[MaxLength(100)]
public string FirstName { get; set; }
[MaxLength(100)]
public string LastName { get; set; }
[MaxLength(100)]
public string City { get; set; }
}
}
电影模型:
namespace SuperHeroesApi.Models
{
public class Movie
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int MovieId { get; set; }
[Required]
[MaxLength(100)]
public string Title { get; set; }
public int Year { get; set; }
public double Rate { get; set; }
public byte [] Poster { get; set; }
[ForeignKey("SuperHero")]
public int HeroId { get; set; }
//public string SuuperHeroName { get; set; }
public virtual SuperHero SuperHero { get; set; }
}
}
dto:
namespace SuperHeroesApi.Otds
{
public class MoviesDtos
{
public string Title { get; set; }
public int Year { get; set; }
public double Rate { get; set; }
public IFormFile Poster { get; set; }
[ForeignKey("SuperHero")]
public int HeroId { get; set; }
}
}
电影控制器:
using SuperHeroesApi.Otds;
namespace SuperHeroesApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class MoviesController : ControllerBase
{
private readonly AppDbContext _dbContext;
private new List<string> _allowedExtention = new List<string> { "jbg", "png" };
private long _maxAllowedPosterSize = 5242880;
public MoviesController(AppDbContext dbContext)
{
_dbContext = dbContext;
}
[HttpGet]
public async Task<IActionResult>GetAllAsync()
{
var movie = await _dbContext.Movies.ToListAsync();
return Ok(movie);
}
[HttpPost]
public async Task <IActionResult> CreateAsync([FromForm] MoviesDtos dto)
{
if (_allowedExtention.Contains(Path.GetExtension(dto.Poster.FileName).ToLower()))
return BadRequest();
using var dataStream = new MemoryStream();
await dto.Poster.CopyToAsync(dataStream);
var movie = new Movie
{
Title = dto.Title,
Year = dto.Year,
Rate = dto.Rate,
Poster = dataStream.ToArray(),
};
await _dbContext.AddAsync(movie);
_dbContext.SaveChanges();
return Ok(movie);
}
}
}
在更改架构之前,您可能已经拥有现有行。现在您正在电影中创建一个新的外键
HeroId
,它不能为空,并且是一个整数,这意味着默认情况下它将为零。这对于现有行来说是一个问题,因为它们将尝试引用一个不存在的 Id 为 0 的 Hero 实体。因此,显而易见的解决方案是使外键可为空并重做迁移
[ForeignKey("SuperHero")]
public int? HeroId { get; set; }
确保您不是自己提供Id,它会自动生成。
如果你的班级是这样的
public class Canditate:Entity,IHasCreationTime
{
[Required]
public String Name { get;set; }
public String Position { get; set; }
public DateTime CreationTime { get; set ; }
public Canditate()
{
CreationTime = DateTime.Now;
}
}