該問題涉及缺少具有2個表的鏈接關係條目。關係多對多 - 自動初始化
我創建了兩個類:
文件:
public class File
{
public int FileId {get; set;}
public string Name{get; set;{
public ICollection<int> TagId {get; set;}
public virtual ICollection<Tag> Tag {get; set;}
}
標籤:
public class Tag
{
public int TagId {get; set;}
public string Name {get; set;}
public ICollection<int> FileId {get; set;}
public ICollection<File> File {get; set;}
}
創建表:
public DbSet<File> Files { get; set; }
public DbSet<Tag> Tags{ get; set; }
在數據庫automaicly創造了進一步的表標籤文件,在哪裏h表之間有關係。
我添加了StartInitializer類,每次重新啓動我到數據庫。裏面的init方法我添加新的記錄:
...
var tags = new List<Tag>
{
new Tag() { TagId = 1, Name = "A"},
new Tag() { TagId = 2, Name = "B"},
new Tag() { TagId = 3, Name = "C"},
new Tag() { TagId = 4, Name = "D"},
new Tag() { TagId = 5, Name = "E"},
new Tag() { TagId = 6, Name = "F"},
new Tag() { TagId = 7, Name = "G"}
};
tags.ForEach(g => context.Tags.Add(g));
context.SaveChanges();
var files = new List<File>
{
new File() { FileId = 1, Name = "1", TagId = new List<int>{1, 3, 2, 4}}
};
files.ForEach(g => context.Files.Add(g));
context.SaveChanges();
...
不幸的是FileETag表項不會自動添加,但在我看來,TagId = new List <int> {1, 3, 2, 4}
應該得到保證。這裏缺少什麼東西?
你能更好的解釋一下這些公共ICollection嗎? –
我認爲那些'公衆ICollection FileId {get; set;}''public ICollection FileId {get;設置;}'是不需要的。而不是上面的'public virtual ICollection Tag {get;設置;}'添加'[InverseProperty(「文件」)]' –
LiranBo