Home > Back-end >  EF Core one-to-many-relations: Sets wanted foreign key into the same column of the primary key and t
EF Core one-to-many-relations: Sets wanted foreign key into the same column of the primary key and t

Time:10-22

For a while I've been puzzling over the following problem: I have a one quality and a sub quality. Now I want to add several sub-qualities to one quality using EF Core. I tried to follow the documentation as good as possible.

This is my model for quality:

public class Quality
{
    [Key]
    [Required]
    public string Name { get; set; }
    public string? Description { get; set; }
    public ICollection<QualitySublevel>? QualitySublevels { get; set; }
}

This is my model for sub quality:

public class QualitySublevel
{
    [Key]
    [Required]
    public string Name { get; set; }
    public string? Description { get; set; }
    public string? QualityName { get; set; }
    public Quality? Quality { get; set; }
}

Then, for example, I have the seeding for the quality with:

public void Configure(EntityTypeBuilder<Quality> builder)
    {
        builder.ToTable(Constants.Quality);
        builder.HasData(
            new Quality
            {
                Name = "Reliability",
                Description = "",
            },
....

And for sub quality the following configuration. Important here is the end with the attempt to assign the subqualities to the qualities.

public void Configure(EntityTypeBuilder<QualitySublevel> builder)
    {
        builder.ToTable(Constants.QualitySublevel);
        builder.HasData(
            new QualitySublevel
            {
                Name = "Availability",
                QualityName = "Reliability"
            },
...

        builder.HasOne(qs => qs.Quality)
        .WithMany(quality => quality.QualitySublevels);

Now when I do a migration the model etc is created for the qualities and also for the sub qualities. However, in the database (SQLite) the foreign key for Quality (QualityName) is not used but the foreign key is apparently the name of the sub-quality. This means that the name of the sub-quality is key and foreign key. Of course, no link is created and no collection of sub-qualities is created in the qualities by seeding. Also I have already tried to add `.HasForeignKey(k => k.QualityName), which unfortunately has not changed anything. Unfortunately, I don't understand here why it doesn't work, since I went by documentation and have several questions already explored.

CodePudding user response:

Try configuring your Quality entity by adding the following:

builder.HasMany(q => q.QualitySublevels).WithOne().HasForeignKey("QualityName");

This will map your QualitySublevels to your Quality entity and might resolve the issue you are having with your QualitySublevels entity.

  • Related