【问题标题】:How to design one to many relationship in efcore?如何在 efcore 中设计一对多关系?
【发布时间】:2020-01-22 16:07:29
【问题描述】:

您好,我正在研究实体框架核心。我有用户表,用户可能是多个项目的一部分。每个项目的用户必须输入时间表数据。例如下面是我的用户表。

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

下面是我的项目表。

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

这里用户可能属于多个项目。现在,对于每个项目,用户都必须输入时间表数据。下面是时间表。

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

我必须在实体框架核心中定义它。一个用户可能是多个项目的一部分,并且用户需要将数据输入到每个项目的时间表中。如何定义与上表的关系?

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

【问题讨论】:

  • 为什么要为 Keys 使用字符串数据类型?
  • 好的,我把它改成int

标签: c# .net ef-core-2.0


【解决方案1】:

假设您要将字符串更改为 int ids,下面的操作是否有效?

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; }
}

【讨论】:

  • 谢谢我会测试。假设在项目类构造函数中是 Public Project() 正确而不是用户?
  • @Niranjan 是的,感谢您指出。我已经更新了我的答案。请检查。
  • 另外,如果我将用户 ID 作为输入传递,我如何获取特定用户的时间表数据? _context.Users.Where(s => s.Id == userid).Include(s => s.Projects) 在此之后如何包含时间表数据?
  • 嗨 Sam 我更改了所有内容并编译没有错误,但考虑如何为每个项目的每个用户制定时间表?我可以知道吗?
  • _context.Users.Include(s => s.Projects.TimeSheetData).Where(s => s.Id == userid)。当您包含 TimeSheetData 时,将自动包含项目。上述语句将返回所有项目,包括给定 userId 的所有 TimeSheetData
猜你喜欢
  • 1970-01-01
  • 2021-10-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多