c# - 实体类型上的导航还没有被添加到模型中,或者被忽略,或者 entityType 被忽略

标签 c# entity-framework asp.net-core dnx entity-framework-core

The navigation 'Tags' on entity type 'Notepad.Models.Note' has not been added to the model, or ignored, or entityType ignored.

public class Note
    {
        public Note()
        {
            CreationDate = DateTime.Now;
            Tags = new HashSet<Tag>();
            Parts = new HashSet<Part>();
        }

        public int ID { get; set; }
        public virtual ICollection<Tag> Tags { get; set; }
        public virtual ICollection<Part> Parts { get; set; }
        public DateTime? CreationDate { get; set; }
    }


public class Tag
    {
        public Tag()
        {
            Notes = new HashSet<Note>();
        }

        public int ID { get; set; }
        public string Name { get; set; }

        public virtual ICollection<Note> Notes { get; set; }
    }

添加迁移时发生:

dnx ef migrations add DbData -c DataDbContext

为什么会这样?

编辑: 数据数据库上下文:

public class DataDbContext : DbContext
    {
        public DbSet<Note> Notes { get; set; }
        public DbSet<Tag> Tags { get; set; }
        public DbSet<Part> Parts { get; set; }
    }

最佳答案

你在那里有多对多关系。正如文档所说:http://docs.efproject.net/en/latest/modeling/relationships.html#id21

尚不支持没有实体类来表示连接表的多对多关系。但是,您可以通过包含连接表的实体类并映射两个单独的一对多关系来表示多对多关系。

所以你必须像这样创建额外的“加入”类:

public class NoteTag
    {
        public int NoteId { get; set; }
        public Note Note { get; set; }

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

然后,替换

 ICollection<Tag> Tags {set;get}

在你的 Note 类中

 ICollection<NoteTag> NoteTags {set;get}

还有标签类:

ICollection<Note> Notes {set;get;}

ICollection<NoteTags> NoteTags {set;get}

然后重写 DbContext 中的 OnModelCreating 方法:

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

            modelBuilder.Entity<NoteTag>()
                .HasOne(pt => pt.Note)
                .WithMany(p => p.NoteTags)
                .HasForeignKey(pt => pt.NoteId);

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

关于c# - 实体类型上的导航还没有被添加到模型中,或者被忽略,或者 entityType 被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34527336/

相关文章:

c# - 如何在 ASP.NET 中将列表从后端传递到前端

c++ - 取决于静态参数包字段的返回类型

asp.net-mvc - 如何处理 ASP.NET Web API 中的 OperationCanceledException?

c# - 如何将文件和 json 对象从 postman 传递到 asp.net 核心 webapi

c# - 谷歌身份验证 ASP.NET Core Web Api

c# - 单行子查询返回多行 Oracle 数据库

c# - C#中的部分透明启动画面

c# - 从命令提示符运行单元测试失败

c# - 保存到数据库时出现 InvalidOperationException

c# - 如何将 ASP.NET Core UserSecrets 部署到生产环境