C#C
C#14mo ago
kianyuen

Migration not reflecting Model correctly

Context: I'm using .NET core 6.0, ASP.NET MVC, trying to initiate the db with Migrations
Got this error:
PostgresException: 23502: null value in column "parent_id" of relation "post" violates not-null constraint DETAIL: Detail redacted as it may contain sensitive data. Specify 'Include Error Detail' in the connection string to include this information.

I clearly defined the ParentId to be nullable here:
    public class Post
    {
        public int Id { get; set; }
        public PostType Type { get; set; }
        public int? ParentId { get; set; }
        public virtual Post Parent { get; set; }
        [InverseProperty("Parent")]
        public virtual ICollection<Post> Answers { get; set; }
        public int? AcceptedAnswerId { get; set; }
        public virtual Post AcceptedAnswer { get; set; }
        public int UserId { get; set; }
        public User User { get; set; }
        [StringLength(255)]
        public string Title { get; set; }
        [Column(TypeName = "text")]
        public string Body { get; set; }
        public virtual ICollection<Tag> Tags { get; set; }
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
        public Post()
        {
            Tags = new HashSet<Tag>();
            Answers = new HashSet<Post>();
        }
    }

Any suggestion on how I can fix this? I think I can just modify the generated migration file, but I'm afraid that would break the migrations.
Was this page helpful?