HasOne not found in EF 6

Kenji Elzerman picture Kenji Elzerman · Jun 11, 2017 · Viewed 8.7k times · Source

I am very new to Entity Framework and I am trying to figure out relations. I have found this code:

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; }
}

I get an error while compiling the code:

'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?)

I have tried to find it on Google and StackOverflow, but the only things I found was how to use it and not why it gives problems. Do I actually miss a reference? If so, which one?

Answer

CodeCaster picture CodeCaster · Jun 11, 2017

HasOne() is an Entity Framework Core method.

In prior versions you use HasOptional() or HasRequired().