【问题标题】:How to model this correctly in Entity Framework?如何在实体框架中正确建模?
【发布时间】:2017-11-04 03:06:28
【问题描述】:

我有一个不知道如何完成的要求,在我现有的数据中,我有一个客户列表,每个客户都应该被分配一个员工成员来与他们一起工作,所以这是一对一的关系还是一个一对多的关系,在如何对数据建模时遇到了麻烦,因为我想弄清楚如何正确地建模。由于可以将一名员工分配给许多不同的客户,我应该如何建模?这看起来正确吗? 我想要的是让表单在输入新客户时从员工表中提取可用的员工列表,最好是名称 我想我可能可以使用 linq 来做到这一点..

    public class Customer
{
    public int CustomerId { get; set; }
    public string Name { get; set; }
    public string BusinessName { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
    public DateTime RequestDate { get; set; }
    public Staff Staff { get; set; }

    public List<CustomerJob> CustomerJobs { get; set; }

}
       public class Staff
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Phone { get; set; }
    public string EMail { get; set; }
    public int CustomerId { get; set; }
}

【问题讨论】:

  • 为什么不让员工列出客户名单?

标签: asp.net-core entity-framework-6


【解决方案1】:

Customer 恰好有 1 个 Staff,而单个 Staff 可能分配给超过 1 个 Customer。所以这是一个一对多关系。

Customer 最好注意它的Staff。它可以称为AssignedStaffStaff itslef 不需要有一个属性来显示它的所有Csutomers。很困难,您可以使用简单的查询提取StaffCustomer 列表。

我推荐的类结构如下:

public class Customer
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }
    public string BusinessName { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
    public DateTime RequestDate { get; set; }
    public Staff AssignedStaff { get; set; }

    public List<CustomerJob> CustomerJobs { get; set; }
}

public class Staff
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }
    public string Phone { get; set; }
    public string EMail { get; set; }
}

用于提取StaffCustomer 列表的查询:

var customers = _dbContext.Customers.Where(x => x.AssignedStaff.Id == staffId);

【讨论】:

  • 谢谢,虽然我希望客户查询返回员工姓名列表,而不是按 ID,但我想不出该怎么做。我的目标是让添加记录变得更容易,而 id 并不完全是用户友好的
  • 如果我理解正确,您需要在下拉框中显示员工列表,以便将任何员工选择为AssignedStaff。因此,您需要在 Staff 上进行简单查询,以根据您的条件(即姓名、电话或电子邮件)提取数据。
  • 是的,这正是我想要的,但由于脚手架视图是强类型的,我不确定如何将它添加到我的视图模型中并让它正常工作。
  • 所以这将是一个 UI 问题而不是实体框架。它提出了一个新问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多