在EF 6中找不到HasOne [英] HasOne not found in EF 6

查看:160
本文介绍了在EF 6中找不到HasOne的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Entity Framework还是很陌生,我正在尝试找出关系。我找到了以下代码:

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

编译代码时出现错误:


'EntityTypeConfiguration'不包含
'HasOne'的定义,也没有扩展方法'HasOne'接受类型'的第一个参数
可以找到EntityTypeConfiguration(您
缺少using指令或程序集引用吗?)

'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上使用,但我发现的唯一问题是如何使用它,而不是为什么会出现问题。我真的错过了参考吗?如果是,是哪一个?

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?

推荐答案

HasOne() 是实体框架核心方法。

HasOne() is an Entity Framework Core method.

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

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

这篇关于在EF 6中找不到HasOne的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆