【问题标题】:Convert SQL query to LINQ method syntax in C#在 C# 中将 SQL 查询转换为 LINQ 方法语法
【发布时间】:2021-08-04 01:31:24
【问题描述】:

我想从 4 个相互关联的表中获取数据。

场景:一个人可以借出属于某个程序的设备

      Database Tables
person          -> Persons Database Table           
device loan     -> Loan Database Table  
device          -> Devices Database Table  
program         -> Programs Database Table

这些是图表中的数据库表:

这是所需的输出:

上面的输出是由以下 SQL 查询产生的:

SELECT A.*, 
COALESCE(ps.first_name,'') AS firstname,
COALESCE(ps.last_name,'') AS lastname,
COALESCE(p.program_name, '') AS program_Name 
FROM devices A 
LEFT JOIN device_loans l ON l.device_id = A.device_id
LEFT JOIN persons ps ON ps.person_id = l.person_id
LEFT JOIN programs p ON A.program_id = p.program_id
WHERE A.device_type ="Tablet" AND  p.program_id = 5;

我想将 SQL 查询转换为 LINQ 方法语法。我试过了 以下方法:

var devices = from ds in _context.Devices
        join p in _context.Programs on ds.ProgramID equals p.Id 
        join l in _context.DeviceLoan on ds.Id equals l.device_id 
        join ps in _context.Persons on l.device_id equals ps.Id 
        where ds.Type == typeName
        where ds.ProgramID == id
        select new Device
              {
                  Id = ds.Id,
                  ProgramID = p.Id,
                  Type = ds.Type,
                  Serial_Number = ds.Serial_Number,
                  Label = ds.Label,
                  Price = ds.Price,
                  Purchase_Date = ds.Purchase_Date,
                  Device_Status = ds.Device_Status
                  
              };

我想要的是创建一个 LINQ 方法语法,其中包括 Database Persons TableDatabase 中的 Firstname 和 Lastname Programs TableDatabase Devices Table 中的数据,就像上面的 SQL 查询一样。

Output: I want all devices of a certain program, loan or not loan with 
        first name & last name of a Person loan too. 

感谢您的帮助

【问题讨论】:

标签: c# mysql sql-server linq


【解决方案1】:

感谢各位的帮助。我创建了以下查询,它给了我想要的。

var devices = _context.Devices.
                    Where(c => c.Type == typeName && c.ProgramID == id).
                    Include(c => c.Program).
                    Include(c => c.DeviceLoans)
                        .ThenInclude(x => x.Persons).
                    ToList();

在.cshtml中

var loan_object = item.DeviceLoans.Where(d=>d.device_id==item.Id).FirstOrDefault()

要获取设备借给的人的姓名,我使用上面的代码行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多