实体类型上的导航尚未添加到模型中,或被忽略,或者实体类型被忽略

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

public class Note { public Note() { CreationDate = DateTime.Now; Tags = new HashSet(); Parts = new HashSet(); } public int ID { get; set; } public virtual ICollection Tags { get; set; } public virtual ICollection Parts { get; set; } public DateTime? CreationDate { get; set; } } public class Tag { public Tag() { Notes = new HashSet(); } public int ID { get; set; } public string Name { get; set; } public virtual ICollection Notes { get; set; } } 

添加迁移时会发生这种情况:

dnx ef migrations添加DbData -c DataDbContext

为什么你认为它会发生?

编辑:DataDbContext:

 public class DataDbContext : DbContext { public DbSet Notes { get; set; } public DbSet Tags { get; set; } public DbSet Parts { get; set; } } 

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

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

所以你必须创建另外的“join”类,如下所示:

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

然后,替换

  ICollection Tags {set;get} 

在你的Note类中

  ICollection NoteTags {set;get} 

以及Tag类:

 ICollection Notes {set;get;} 

 ICollection NoteTags {set;get} 

然后覆盖DbContext中的OnModelCreating方法:

 protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() .HasKey(t => new { t.NoteId, t.TagId }); modelBuilder.Entity() .HasOne(pt => pt.Note) .WithMany(p => p.NoteTags) .HasForeignKey(pt => pt.NoteId); modelBuilder.Entity() .HasOne(pt => pt.Tag) .WithMany(t => t.NoteTags) .HasForeignKey(pt => pt.TagId); } 

我使用的是EF 7,这个问题花了我大约2个小时的时间。 :)所以,这是一个简单的解决方案 – 我有一个像这样的个人资料类 –

 [Table("Profile")] public class Profile { public Profile() { } [Column(Order = 1)] [Key] public Guid ProfileID { get; set; } [JsonIgnore] public virtual ICollection StudentProfileMap { get; set; } [JsonIgnore] public virtual ICollection ParentProfileMap { get; set; } } 

我在另一个名为“StudentLivingWith”的表中使用ProfileID作为F-Key引用。 (是的,我知道这个名字有点奇怪。:))正如你在下面的类中看到的那样,“StudentProfileID”和“ParentProfileID”这两列引用了我的“Profile”表的同一列“profileID”。

 [Table("StudentLivingWith")] public class StudentLivingWith { public StudentLivingWith() { } [Column(Order = 1)] [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int StudentLivingWithID { get; set; } [Column(Order = 2)] [ForeignKey("StudentProfileID")] public Guid StudentProfileID { get; set; } [Column(Order = 3)] [ForeignKey("ParentProfileID")] public Guid ParentProfileID { get; set; } [JsonIgnore] [InverseProperty("StudentProfileMap")] public virtual ICollection StudentProfile { get; set; } [JsonIgnore] [InverseProperty("ParentProfileMap")] public virtual ICollection ParentProfile { get; set; } } 

所以结论是 – 你只需要在引用上添加[InverseProperty]标签,这个简单的解决方案就可以解决这个问题。

我希望这将有所帮助。 谢谢。