asp.net Microsoft.EntityFrameworkCore.DbUpdateException:保存实体更改时出错,有关详细信息,请参见内部异常

xu3bshqb  于 2023-08-08  发布在  .NET
关注(0)|答案(2)|浏览(214)

我正在学习Webapi,所以我试图建立一个简单的API连接到SQL服务器,我得到了这个错误,当我添加新的电影数据
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; }


    }
}


MoviesController:

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);
        }



    }
}

lymgl2op

lymgl2op1#

在对架构进行更改之前,您可能已经有了现有的行。现在,您正在movie中创建一个新的外键HeroId,它不能为null和整数,这意味着默认情况下它将是零。这对现有行来说是一个问题,因为它们将尝试引用ID为0的Hero实体,而该实体并不存在。因此,显而易见的解决方案是使外键可为空,然后重新进行迁移

[ForeignKey("SuperHero")] 
public int? HeroId { get; set; }

字符串

yh2wf1be

yh2wf1be2#

确保你不是自己给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;    
        }
    }

字符串

相关问题