一对多查询,Linq,实体框架

时间:2017-11-08 20:39:24

标签: c# linq entity-framework-6

我的数据库中有两个模型,CompanyEmployee,有一对多的关系(一个公司可以有很多员工)。

我想获得员工及其公司的名单,并且可以访问所有员工信息和相关公司(人员是我的员工模型[表格称为人员],公司 - 公司模型)

所以我写道:

List<Person> people = new List<Person>();

using (var db = new DataContext())
{
    var list_of_people = db.People;

    foreach (Person p in list_of_people)
    {
        people.Add(p);
    }
}

现在我有Person个对象列表,但它没有关于公司名称的信息。

有人可以解释我如何获得员工及其公司的名单吗?

该查询会返回什么? A DbSet

public class Person
    {
        public Person()
        {

        }
        public int PersonId { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
        public string Job { get; set; }
        public int Phone { get; set; }
        public int Mobile { get; set; }

        public Company Company { get; set; }
    }

public class Company
    {
        public Company()
        {

        }
        public int Id { get; set; }
        public string Name { get; set; }
        public int NIP { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public int Code { get; set; }
        public int Phone { get; set; }
        public string Notes { get; set; }

        public ICollection<Person> Person { get; set; }
    }

3 个答案:

答案 0 :(得分:0)

更具惯用力,

List<Person> people;

using (var db = new DataContext()) {
    people = db.People.ToList();
}

假设您没有从PersonCompany的EF连接,您可以进行左连接:

var employeesWithCompany = from p in db.People
                           join c in db.Company on p.CompanyID == c.ID into cj
                           from c in cj.DefaultIfEmpty()
                           select new { p, c };

答案 1 :(得分:0)

现在我已经这样做了:

using (var db = new DataContext())
{
    var new_list = from p in db.People
                   join c in db.Companies on p.Company.Id equals c.Id
                   select new { p, c };
}

此代码有效,我在LinqPad中检查了它并显示了良好的结果,但我不知道如何迭代new_list并获取我想要的数据:(

此外,我觉得我没有使用我在模型中添加的关系。如果我有一对多的关系,我应该可以使用People模型即时访问有关公司的所有信息,而无需对公司数据进行额外查询,因为一个人只能拥有一家公司...

答案 2 :(得分:0)

如果您想拥有导航属性,那么人员及其公司的列表非常简单:

using (var db = new DataContext())
{
    var peopleWithCompany = db.People.Include(p => p.Company).ToList();
}

现在,如果你想迭代:

foreach (var currentPerson in peopleWithCompany)
{
     var personName = currentPerson.Name;
     var job= currentPerson.Job;
     ...
     var companyName = currentPerson.Company.Name;
     var companyAddress = currentPerson.Company.Address;
     ...
}