如何在efcore中设计一对多关系?

How to design one to many relationship in efcore?

您好,我正在研究 entity framework 核心。我有用户 table 并且用户可能是多个项目的一部分。每个项目的用户必须输入时间 sheet 数据。例如下面是我的用户 table.

public class User
    {
        [Key]
        public string Id { get; set; }
        public string name { get; set; }
        public string emailId { get; set; }
    }

下面是我的项目table。

 public class Project
    {
        [Key]
        public string Id { get; set; }
        public string Name { get; set; }
        public string userId { get; set; }
    }

此处用户可能属于多个项目。现在对于每个项目用户必须输入 timesheet 数据。下面是时间sheet table.

public class TimeSheetData
    {
        [Key]
        public string id { get; set; }
        public string project_id { get; set; }
        public string hours_logged { get; set; }
    }

我必须在 entity framework 核心中定义它。一个用户可能是多个项目的一部分,用户需要为每个项目输入数据到 timesheet。我如何定义与上述 table 相关的关系?

在用户 table 中是否需要添加类似 Public List<Project> Projects 的内容?同样在项目 table Public List<Timesheet> Timesheets 中,我必须在这里定义一些东西。有人可以帮助我理解这一点吗?任何帮助将不胜感激。谢谢

假设您要将字符串更改为 int id,下面的内容是否有效?

public class User
{
    public User()
    {
        this.Projects = new HashSet<Project>();
    }
    [Key]
    public int Id { get; set; }
    public string name { get; set; }
    public string emailId { get; set; }
    public virtual ICollection<Project> Projects { get; set;}
}

public class Project
{   
    public Project()
    {
        this.TimeSheetData = new HashSet<TimeSheetData>();
    }
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public int userId { get; set; }
    [ForeignKey("userId")]
    public virtual User User {get; set; }
    public virtual ICollection<TimeSheetData> TimeSheetData { get; set;}
}

public class TimeSheetData
{
    [Key]
    public int id { get; set; }
    public int project_id { get; set; }
    [ForeignKey("project_id")]
    public virtual Project Project {get; set; }
    public string hours_logged { get; set; }
}