Pio*_*rek 6 c# entity-framework entity-framework-core dnx asp.net-core
实体类型"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; }
}
Run Code Online (Sandbox Code Playgroud)
添加迁移时会发生这种情况:
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; }
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*cki 11
你有许多一对多的关系存在.正如文档所述: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; }
}
Run Code Online (Sandbox Code Playgroud)
然后,替换
ICollection<Tag> Tags {set;get}
Run Code Online (Sandbox Code Playgroud)
在你的Note类中
ICollection<NoteTag> NoteTags {set;get}
Run Code Online (Sandbox Code Playgroud)
以及Tag类:
ICollection<Note> Notes {set;get;}
Run Code Online (Sandbox Code Playgroud)
至
ICollection<NoteTags> NoteTags {set;get}
Run Code Online (Sandbox Code Playgroud)
然后覆盖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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2508 次 |
| 最近记录: |