简体   繁体   中英

Cannot resolve symbol 'HasRequired' Entity Framework Core

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM