繁体   English   中英

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

[英]One to Many query, Linq, Entity Framework

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

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

所以我写道:

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对象的列表,但是没有有关公司名称的信息。

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

该查询将返回什么? 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; }
    }

更习惯地说,

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

现在,我已经这样做了:

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模型即时访问有关公司的所有信息,而无需对公司数据进行额外查询,因为一个人只能拥有一个公司...

如果您想要一个人及其公司的清单,这很简单,因为您具有导航属性:

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

暂无
暂无

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

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