實體類型“Notepad.Models.Note”上的導航“標籤”尚未添加到模型中,或被忽略,或者實體類型被忽略。
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添加DbData -c DataDbContext
為什麼你認為它會發生?
編輯: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
尚不支持沒有實體類來表示連接表的多對多關係。但是,您可以通過包含連接表的實體類並映射兩個單獨的一對多關係來表示多對多關係。
所以你必須創建另外的“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<Tag> Tags {set;get}
在你的Note類中
ICollection<NoteTag> NoteTags {set;get}
以及Tag類:
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);
}
我使用的是EF 7,這個問題花了我大約2個小時的時間。 :)所以,這是一個簡單的解決方案 - 我有一個像這樣的個人資料類 -
[Table("Profile")]
public class Profile
{
public Profile()
{
}
[Column(Order = 1)]
[Key]
public Guid ProfileID { get; set; }
[JsonIgnore]
public virtual ICollection<StudentLivingWith> StudentProfileMap { get; set; }
[JsonIgnore]
public virtual ICollection<StudentLivingWith> 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<Profile> StudentProfile { get; set; }
[JsonIgnore]
[InverseProperty("ParentProfileMap")]
public virtual ICollection<Profile> ParentProfile { get; set; }
}
所以結論是 - 你只需要在引用上添加[InverseProperty]標籤,這個簡單的解決方案就可以解決這個問題。
我希望這將有所幫助。謝謝。