【发布时间】:2018-12-11 14:40:25
【问题描述】:
我使用免费版的 LinqPAD。
我只有带有代码的 .cs 文件。我无法运行和调试它。我没有数据库。
(而且我不是 C# 程序员。)
我需要将 Linq 查询转换为原始 SQL(MsSql) 查询。我想看普通的 SQL 查询。
所以我打开 LinqPAD 并编写硬编码的对象/类,它们代表数据库中的三个表。
我切换到“C#程序”。
public class ContactModel
{
public int UserSecondId { get; set; }
public int UserId { get; set; }
public int OrganizationId { get; set; }
public bool IsPrimary { get; set; }
}
class Contacts
{
public int OrganizationId { get;set; }
public int UserId { get;set; }
public char IsPrimary { get;set; }
}
class Organizations
{
public int Id { get;set; }
public int SecondId { get;set; }
}
class Users
{
public int Id { get;set; }
public char IsActive { get;set; }
public int SecondId { get;set; }
}
void Main()
{
List<Contacts> Contacts = new List<Contacts>();
Contacts.Add(new Contacts { OrganizationId = 1, UserId = 1, IsPrimary = 'Y' });
Contacts.Add(new Contacts { OrganizationId = 2, UserId = 1, IsPrimary = 'Y' });
List<Organizations> Organizations = new List<Organizations>();
Organizations.Add(new Organizations { Id = 1, SecondId = 1 });
Organizations.Add(new Organizations { Id = 2, SecondId = 2 });
List<Users> Users = new List<Users>();
Users.Add(new Users { Id = 1, SecondId = 1, IsActive = 'Y' });
Users.Add(new Users { Id = 2, SecondId = 1, IsActive = 'Y' });
int[] orgSecondIdList = { 1, 2 };
var query =
from contacts in Contacts
from orgs in Organizations.Where(o => o.Id == contacts.OrganizationId)
from users in Users.Where(o => o.Id == contacts.UserId)
where contacts.IsPrimary == 'Y' && users.IsActive == 'Y' &&
orgSecondIdList.Contains(orgs.SecondId)
select new ContactModel
{
OrganizationId = contacts.OrganizationId,
UserId = contacts.UserId,
UserSecondId = users.SecondId
};
query.Dump();
}
我按下运行键。
LinqPAD 向我展示了 Vizualizer 中的表格。但是 SQL 选项卡是空的。
怎么了?我可以获得原始 SQL 查询吗?
赞SELECT ... FROM ...
【问题讨论】:
-
您的代码完全没有与 SQL 或数据库相关/依赖于 SQL 或数据库的功能,它包含大量基本类和 linq 查询。没有任何东西处于可运行状态,您无法从实际代码中执行和捕获生成的 SQL。
-
是否可以将 Linq 查询转换为 SQL?我可以在表格中看到正确的结果。而且我不明白为什么我看不到向我展示这张表的 SQL?是否有工具可以将 Linq 转换为没有真实数据和数据库的普通 SQL? (因为我看不出它有什么困难)
-
您没有看到任何 SQL,因为您没有执行任何 SQL! LinqPad 中的 Linq2Sql 代码将您的 linq 代码转换为 SQL,但由于您没有使用它,因此没有什么可转换的!
-
好的,谢谢。是否有可能在没有数据库和调试的情况下将 Linq 代码(大量代码)转换为 SQL?我认为它没有任何困难,因为我们需要从一种传统语法转换为另一种传统语法(不检查真实数据)。例如
from contacts in Contacts是SELECT ... FROM Contacts AS contacts -
LINQ to SQL 或 EF 生成的 SQL 在很大程度上取决于所使用的数据库提供程序,并且可能会有所不同 - 有些提供程序根本不使用 SQL。例如,您可以使用 IQ 驱动程序创建简单的本地 SQLite 数据库,然后查看生成的 SQLite SQL。
标签: c# linq linq-to-sql linqpad