如何用linq连接两个表?

时间:2017-02-01 20:36:06

标签: c# entity-framework linq

我正在尝试使用基于id的linq加入我的两个表,到目前为止这是无关紧要的。

以下是我的模型的外观:

  public class WorkRole
    {

        public int WorkRoleId { get; set; }
        public string RoleName { get; set; }
        public string RoleDescription { get; set; }
        public int CompanyId { get; set; }
        public virtual Company Company { get; set; }
        public virtual ICollection<WorkRolesUsersDetails> WorkRolesUsersDetails { get; set; }
    }



public class WorkRolesUsersDetails
    {

        public int WRUDId { get; set; }

        public int? WorkRoleId { get; set; }


        public string UserDetailsId { get; set; }


        public virtual WorkRole WorkRole { get; set; }

        public virtual UserDetails UserDetails { get; set; }

        public DateTime FocusStart { get; set; }
        public DateTime FocusEnd { get; set; }

        public bool isActive { get; set; }
    }

我试图从第一个表中获取WorkRoleId,RoleName,RoleDescription和CompanyId,并从第二个表中获取UserDetailsId,FocusStart,FocusEnd和isActive。

我的想法最远的是:

var query = db.WorkRoles.Join(db.WorkRolesUsersDetails,x => x.WorkRoleId,y => y.WorkRoleId,(x, y) => new { wr = x, wrud = y });  

但遗憾的是,它没有奏效。我只是不了解linq并且在这里得不到其他问题/答案。请帮忙。

2 个答案:

答案 0 :(得分:2)

加入2个表的代码是:

var list = db.WorkRoles.
                Join(db.WorkRolesUsersDetails,
                o => o.WorkRoleId, od => od.WorkRoleId,
                (o, od) => new
                {
                    WorkRoleId= o.WorkRoleId
                    RoleName= o.RoleName,
                    RoleDescription= o.RoleDescription,
                    CompanyId= o.CompanyId,
                    WRUDId= od.WRUDId,
                    UserDetailsId= od.UserDetailsId,
                    FocusStart=od.FocusStart,
                    FocusEnd=od.FocusEnd
                })

答案 1 :(得分:1)

如果您正在使用EF,我可以建议它包含令人难以置信的包含声明。如果您分配了外键。它基本上可以获得其他数据。

version: '2'
services:
  db:
    image: postgres
    environment:
      POSTGRES_USER: dbuser
      POSTGRES_PASSWORD: dbpw
      PGOPTIONS: "-c track_activities=on -c track_counts=on -c track_io_timing=on"

手动组合而不使用导航上下文选项。

static void Main(string[] args)
{
  using (var context = new TesterEntities())
  {
    var peopleOrders = context.tePerson.Include("teOrder").First(p => p.PersonId == 1).teOrder.ToList();
    peopleOrders.ForEach(x => Console.WriteLine($"{x.OrderId} {x.Description}"));
  }
}