c# - 在 EF 6 中找不到 HasOne

标签 c# entity-framework ef-fluent-api

我是 Entity Framework 的新手,我正在尝试找出关系。我找到了这段代码:

class MyContext : DbContext
{
    public DbSet<Post> Posts { get; set; }
    public DbSet<Tag> Tags { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<PostTag>()
            .HasKey(t => new { t.PostId, t.TagId });

        modelBuilder.Entity<PostTag>()
            .HasOne(pt => pt.Post)
            .WithMany(p => p.PostTags)
            .HasForeignKey(pt => pt.PostId);

        modelBuilder.Entity<PostTag>()
            .HasOne(pt => pt.Tag)
            .WithMany(t => t.PostTags)
            .HasForeignKey(pt => pt.TagId);
    }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public List<PostTag> PostTags { get; set; }
}

public class Tag
{
    public string TagId { get; set; }

    public List<PostTag> PostTags { get; set; }
}

public class PostTag
{
    public int PostId { get; set; }
    public Post Post { get; set; }

    public string TagId { get; set; }
    public Tag Tag { get; set; }
}

编译代码时出现错误:

'EntityTypeConfiguration' does not contain a definition for 'HasOne' and no extension method 'HasOne' accepting a first argument of type 'EntityTypeConfiguration' could be found (are you missing a using directive or an assembly reference?)

我试图在 Google 和 StackOverflow 上找到它,但我找到的唯一东西是如何使用它,而不是它为什么会出现问题。我真的错过了引用吗?如果有,是哪一个?

最佳答案

HasOne()是一个 Entity Framework Core 方法。

在以前的版本中,您使用 HasOptional() or HasRequired() .

关于c# - 在 EF 6 中找不到 HasOne,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44481675/

相关文章:

c# - 存储过程和 C# SqlDataReader 返回的行数少于预期

c# - UDP原始数据在应用程序和wireshark中有所不同

c# - 在 Entity Framework 中按子项排序不返回排序列表

entity-framework - DbContext 释放后枚举成功

c# - 动态 SQL 查询 Entity Framework

c# - 强制Linq不延迟执行

c# - Entity Framework 通用存储库,包括通过参数的属性

c# - SqlClient.SqlException : Invalid column name ClassNameId While fetching data from Fluent API 异常

c# - 使用流畅的 API 编写第一类代码