使用LINQ从外键表获取数据

时间:2018-01-24 04:23:47

标签: c# linq

我有2张桌子

DeviceType表

id   Name 
1    Device Type 1
2    Device Type 2

设备表

id   Name     Device Type Id (fk)
1    Device1  1
2    Device2  1
3    Device3  2

我想要的是使用LINQ Methods从设备表中查询设备类型名称的数据。我无法在这里找到Include方法。

我试图在结果中得到这个

id Name     DeviceType Name
1  Device1  Device Type 1
2  Device2  Device Type 1
3  Device3  Device Type 2

3 个答案:

答案 0 :(得分:2)

var device = from g in db.Devices
        join m in db.DeviceType on g.DeviceTypeId equals m.Id  
        select new 
        {
          Id = g.Id,
          Name = g.Name,
          DeviceTypeName = m.Name
        };

或者您可以尝试类似

的内容
var device = db.Devices
             .Join(db.DeviceType,
                 g => g.Id,      // Device Table Id 
                 m => m.Id,      // DeviceType Table Id
                 (g, m) => new { 
                               Id = g.Id, 
                               Name = g.Name, 
                               DeviceTypeName = m.Name 
              }) 
             .Where(deviceTyp => deviceTyp.g.ID == Id);     
             // where condition for g.DeviceTypeId equals m.Id  

答案 1 :(得分:1)

除非您想要获取相关实体,否则无需使用.Include。你可以这样做:

context.Devices.Where(your conditions here)
      .Select(d=>new {Id = d.id, Name = d.Name, DeviceTypeName = d.DeviceType.Name})

你不需要做join,因为存在FK关系(看起来像是问题),EF应该选择关系

答案 2 :(得分:0)

List<DeviceType> deviceTypeList = new List<DeviceType>() { 
            new DeviceType { id = 1, Name = "Device Type 1" }, 
            new DeviceType { id = 2, Name = "Device Type 2" } };

List<Device> deviceList = new List<Device>() { 
            new Device { id = 1, Name = "Device1", DeviceTypeId = 1 },
            new Device { id = 2, Name = "Device2", DeviceTypeId = 1 },
            new Device { id = 3, Name = "Device3", DeviceTypeId = 2 } };

//Linq
var query = from device in deviceList
        join type in deviceTypeList
        on device.DeviceTypeId equals type.id
        select new { Id = device.id, Name = device.Name,
        DeviceTypeName = type.Name };


//Or lambda expressions
var query = deviceList.Join(deviceTypeList,
        device => device.DeviceTypeId,
        type => type.id,
        (device, type) => new { Id = device.id, Name = device.Name, 
        DeviceTypeName = type.Name });