Entity Framework 6 one to many relationship

眉间皱痕 提交于 2021-01-28 08:14:53

问题


I develop web application with Entity framework 6.

I have a model Folder that contains a list of Letter object.

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:

  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?


回答1:


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.




回答2:


Yes, they will be contained in the Folder's list, you have to modify your virtual property to be a collection of Folder. Then if you try to add or retrieve folders to a specific letter select the letter by id and your folders should be there. For more information you can check here



来源:https://stackoverflow.com/questions/35341333/entity-framework-6-one-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!