Cannot resolve symbol 'HasRequired' Entity Framework Core

Viewed 3242

I'm trying to connect two tables by means of code in C# with Entity Framework Core.

The classes are:

public class roll
{
    [key]
    public int rollId { get; set; }

    public List<pieces> pieces { get; set; }
}

public class pieces
{
    [Key]
    public int pieceId { get; set; }
    public int quantity { get; set; }
    public decimal price { get; set; }
}

In my DbContext, I have the following method:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<roll>()
                .HasRequired(m => m.quantity)
                .WithMany(m => m.pieces)
                .HasForeignKey(m => m.pieceId);

    base.OnModelCreating(modelBuilder);
}

HasRequired turns red and gives this message:

EntityTypeBuilder does not contain a definition for HasRequired.

The project has added a reference to Microsoft.EntityFrameworkCore.Relational. I have recompiled the solution, closed and opened visual studio and I cannot solve that HasRequired stops being red

What is wrong with my code?

2 Answers

You should change your code for .net core EF, they just removed HasRequired and replace it with HasOne for one-to-one relationship and HasMany for one-to-many relations. You Can Also add .IsRequired() for required relations. Good Luck.

modelBuilder.Entity<roll>()
            .HasOne(m => m.quantity).IsRequired()
            .WithMany(m => m.pieces)
            .HasForeignKey(m => m.pieceId);

You can find complete documentation here : Documentation link

Entity Framework Core does not have HasRequired() - that's an old Entity Framework <=6 (.NET Framework) method.

EF Core instead uses HasOne(). You can see more on their official documentation here.

Related