简体   繁体   English

实体框架6一对多关系

[英]Entity Framework 6 one to many relationship

I develop web application with Entity framework 6. 我使用Entity Framework 6开发Web应用程序。

I have a model Folder that contains a list of Letter object. 我有一个包含Folder对象列表的模型Folder。

My letter object: 我的来信对象:

public class Letter
{ 
    [Key]
    public int Id

    [ForeignKey("Folder")]
    public int FolderId {get; set;}

    public virtual Folder Folder {get; set;}
}

I have 2 dbsets in my DbContext: 我的DbContext中有2个dbset:

  DbSet<Folder>
  DbSet<Letter>

My question is what happens when I add a new Letter? 我的问题是,当我添加新字母时会发生什么? If I later on fetch the folder I added the letters, will those letters be contained in the folder's letters list? 如果以后再提取添加字母的文件夹,这些字母是否会包含在文件夹的字母列表中?

Yes, they will be contained in the Folder 's list, you have to modify your virtual property to be a collection of Folder . 是的,它们将包含在Folder的列表中,您必须将virtual属性修改为Foldercollection Then if you try to add or retrieve folders to a specific letter select the letter by id and your folders should be there. 然后,如果您尝试向特定字母添加或检索文件夹,请按ID选择字母,并且您的文件夹应该在那里。 For more information you can check here 欲了解更多信息,请点击这里

So this should your model look like 所以你的模型应该看起来像

public class Folder
{
 public int Id{get;set;}
 public virtual ICollection<Letter> Letters{get;set;}
}

public class Letter
{
public int Id{get;set;}
public int FolderId{get;set;}
public virtual Folder Folder{get;set;}

}

all the best. 祝一切顺利。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM