LINQ JOIN两个表并查看两列

时间:2015-11-25 09:11:43

标签: c# .net linq wcf

我有两张桌子

  

tblPhases

  

tblTruck

我加入了这两个,但我似乎无法在两个表中同时使用这两列。

Phase.cs

public class Phases
{
    public int Id { get; set; }

    public int TruckId { get; set; }
    public virtual RTrucks Truck { get; set; }

    public string Checkin { get; set; }

    public string ChassisPrep { get; set; }

    public string Floor { get; set; }

    public string Body { get; set; }

    public string Paint { get; set; }

    public string Finished { get; set; }

}

RTruck.cs

public class RTrucks
{
    public int Id { get; set; }

    public string ChassisManufacturer { get; set; }

    public string ChassisModel { get; set; }
}

Service.cs

[OperationContract]
    List<Phases> GetPhasesbyTruck(int TruckId);

Service.svc.cs

public List<Phases> GetPhasesbyTruck(int TruckId)
    {
        TruckDb db = new TruckDb();

        List<Phases> r = new List<Phases>();

        var join = from p in db.RTrucks
                   join t in db.Phases
                   on p.Id
                   equals t.TruckId
                   where t.Id == TruckId
                   select p;


        foreach (var item in join)
        {
            r.Add(new Phases()
            {
   //this is not the actual coding but just a demonstration of what is 
   //actually happening                                                                                         
   //    Phases item like Id = tblTruck item like truckId        
            });
        }
        return r;

    }

我不能只从tbltrucks表中调用tblPhases表中的列,还能如何在foreach中一起使用Phases.cs和RTruck.cs,这样我才能访问这两个类项?

2 个答案:

答案 0 :(得分:2)

首先,遵循代码

var join = from p in db.RTrucks
           join t in db.Phases
           on p.Id equals t.TruckId
           select p;

足以在两个表之间建立连接。你不需要为它添加额外的where子句。其次,您可以在答案中选择Arianit提及的两个表中的属性,也可以像上面的查询一样选择Phases,然后您可以通过导航属性访问Truck,例如

foreach (var p in join){
    int truckId = p.Truck.Id;
    string chesis = p.Truck.ChassisManufacturer;
    string model = p.Truck.ChassisModel;
}

第二种方法的好处是您不需要新类来填充两个表中的属性。您可以通过导航属性访问所有信息。

答案 1 :(得分:1)

试试这个:

var join = from p in db.RTrucks
           join t in db.Phases
           on p.Id equals t.TruckId
           select new {TruckName = p.TruckName, //depends from your table column name
           PhasesName = t.PhaseName
           };

foreach (var item in join)
{
     Console.WriteLine(item.TruckName + "\t" + item.PhaseName);
 }

从你的linq中删除where