简体   繁体   English

无法解析符号“HasRequired”实体框架核心

[英]Cannot resolve symbol 'HasRequired' Entity Framework Core

I'm trying to connect two tables by means of code in C# with Entity Framework Core.我正在尝试通过 C# 中的代码与 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:在我的DbContext中,我有以下方法:

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: HasRequired变为红色并给出以下信息:

EntityTypeBuilder does not contain a definition for HasRequired. EntityTypeBuilder 不包含 HasRequired 的定义。

The project has added a reference to Microsoft.EntityFrameworkCore.Relational .该项目添加了对Microsoft.EntityFrameworkCore.Relational的引用。 I have recompiled the solution, closed and opened visual studio and I cannot solve that HasRequired stops being red我已经重新编译了解决方案,关闭并打开了 Visual Studio,但我无法解决HasRequired停止变红的问题

What is wrong with my code?我的代码有什么问题?

Entity Framework Core does not have HasRequired() - that's an old Entity Framework <=6 (.NET Framework) method. Entity Framework Core 没有HasRequired() - 这是一个旧的 Entity Framework <=6 (.NET Framework) 方法。

EF Core instead uses HasOne() . EF Core 改为使用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.您应该更改 .net 核心 EF 的代码,他们只是删除HasRequired并将其替换为HasOne用于一对一关系,而HasMany则用于一对多关系。 You Can Also add .IsRequired() for required relations.您还可以为所需的关系添加.IsRequired() 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您可以在此处找到完整的文档: 文档链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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