简体   繁体   English

建立一对多关系

[英]Creating a one to many relationship

I am trying to create a one ( Project ) to many ( ActionLog ) relationship between the following tables: 我正在尝试在下表之间创建一对多( Project )对多( ActionLog )关系:

public class Projects {
    [Key]
    public int Id { get; set; }
    public string Name { get; set; } //I cut out most of the props as they were not relevant
   }

//They exist in two different .cs files. 

public class ActionLog {
     [Key]
     public int Id { get; set;}
     public string Information {get; set;}
     public ProjectsId {get; set;}
   }

Currently, in my viewmodel, I am doing a linq select for all entries that match my ProjectTableId and putting it into a list for each instance of Project . 当前,在我的viewmodel中,我对所有与ProjectTableId匹配的条目进行linq select,并将其放入每个Project实例的列表中。

I fear that this approach is extremely inefficient as it queries the database for every single entry of Projects. 我担心这种方法效率极低,因为它会在数据库中查询项目的每个条目。 I know eager(?) loading would be best in this case, but I don't know how to implement it. 我知道在这种情况下,最好使用eager(?)加载,但我不知道如何实现。

Tables can look like this: (Structure-wise) 表格如下所示:(在结构上) 在此处输入图片说明 * Again the actual tables are necessarily complicated, so I cut out the unnecessary props for simplicity sake. * 实际的表再次很复杂,因此为了简单起见,我删去了不必要的道具。

Traditionally, you'd have an ICollection of your many-related items: 传统上,您会拥有许多相关项目的ICollection

public class Project
{
    ...

    public virtual ICollection<ActivityLog> ActivityLogs { get; set; }
}

With that, then, you can include the logs when querying the projects: 这样,您就可以在查询项目时包括日志:

var projects = db.Projects.Include(m => m.ActivityLogs)

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

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