实体类型的导航未添加到模型中,或被忽略,或实体类型被忽略 [英] The navigation on entity type has not been added to the model, or ignored, or entityType ignored

查看:22
本文介绍了实体类型的导航未添加到模型中,或被忽略,或实体类型被忽略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实体类型Notepad.Models.Note"上的导航标签"尚未添加到模型中,或被忽略,或实体类型被忽略.

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 迁移添加 DbData -c DataDbContext

dnx ef migrations add DbData -c DataDbContext

你认为它为什么会发生?

Why do you think it happens?

数据数据库上下文:

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

You have Many-to-many relationship there. As the documentation says: http://docs.efproject.net/en/latest/modeling/relationships.html#id21

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

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

So you must create additional "join" class like this:

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 类中

in your Note class to

 ICollection<NoteTag> NoteTags {set;get}

还有标签类:

ICollection<Note> Notes {set;get;}

ICollection<NoteTags> NoteTags {set;get}

然后覆盖 DbContext 中的 OnModelCreating 方法:

and then override OnModelCreating method in DbContext:

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

这篇关于实体类型的导航未添加到模型中,或被忽略,或实体类型被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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