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/