Entity Framework multi level inheritance using fluent

Viewed 41

I get an error when I want to create a multi-level table with fluent api for migration on Entity framework.

but I got fail:

SQLite Error 19: 'FOREIGN KEY constraint failed'.

The table structures are as follows:

    Base Entity just for Id

        public class MainArt : BaseEntity
{

    public Paper Paper { get; set; }
    public int PaperId { get; set; }
}


    public class Paper : BaseEntity
{
    public string Name { get; set; }
    public string PaperPrice { get; set; }
    public ColorType ColorType { get; set; }
    public int ColorTypeId { get; set; }
}


    public class ColorType : BaseEntity
{
    public string Name { get; set; }
}

MainArt --> Paper --> ColorType

EF Fluent as below:

MainArt:

        public void Configure(EntityTypeBuilder<MainArt> builder)
    {

        builder.Property(p => p.Id).IsRequired();
        builder.HasOne(p => p.Paper).WithMany().HasForeignKey(p => p.PaperId);

    }

Paper:

        public void Configure(EntityTypeBuilder<Paper> builder)
    {

        builder.Property(p => p.Id).IsRequired();
        builder.Property(p => p.Name).IsRequired().HasMaxLength(100);
        builder.Property(p => p.PaperPrice).IsRequired();
        builder.HasOne(p => p.ColorType).WithMany().HasForeignKey(p => p.ColorTypeId);

    }
}

ColorType and Paper created with migration but MainArt failed.

I searched the web and i think iam missing something. ToTable or one-to-many i don't know.

Thanks.

1 Answers

I found out why it is giving exception. The code is not wrong.

Failure to create one of the child tables causing the error.

Migration and seeding worked correctly when I created the child table correctly.

Related