You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET 6 MVC中如何用FromSqlRaw执行含连接、联合的复杂SQL查询

在ASP.NET 6 MVC中执行包含JOIN、UNION的复杂SQL查询

一、使用FromSqlRaw执行JOIN查询

如果你习惯用原生SQL,直接编写包含JOIN的语句即可,核心是确保查询结果能映射到对应的实体类或DTO(数据传输对象),同时必须参数化查询避免SQL注入风险。

示例:两表关联查询

假设你有Products和Categories表,要查询产品名称、类别名称和价格:

  1. 定义DTO接收查询结果:
public class ProductCategoryDto
{
    public string ProductName { get; set; }
    public string CategoryName { get; set; }
    public decimal Price { get; set; }
}
  1. 在DbContext中注册该DTO(非实体类可通过DbSet声明):
public DbSet<ProductCategoryDto> ProductCategoryDtos { get; set; }
  1. 执行JOIN查询:
var targetCategoryId = 2;
var productsWithCategories = _context.ProductCategoryDtos
    .FromSqlRaw(@"
        SELECT p.ProductName, c.CategoryName, p.Price
        FROM Products p
        INNER JOIN Categories c ON p.CategoryId = c.Id
        WHERE c.Id = {0}", targetCategoryId)
    .ToList();

注意:用{0}作为参数占位符,EF Core会自动处理参数化,禁止直接拼接字符串传递参数。

二、使用FromSqlRaw执行UNION查询

UNION用于合并多个查询的结果集,要求各查询的列数、列类型完全匹配,同样可映射到实体或DTO。

示例:合并两类产品的查询结果

要查询所有价格高于200的产品,以及所有库存为0的产品(自动去重):

var combinedProducts = _context.Products
    .FromSqlRaw(@"
        SELECT Id, ProductName, Price, Stock FROM Products WHERE Price > 200
        UNION
        SELECT Id, ProductName, Price, Stock FROM Products WHERE Stock = 0")
    .ToList();

若需保留重复记录,替换为UNION ALL即可。

三、用EF Core LINQ实现JOIN和UNION(类型安全)

除原生SQL外,EF Core的LINQ查询具备类型安全性,编译阶段就能发现错误,适合逻辑相对清晰的场景。

LINQ JOIN示例

var targetCategoryId = 2;
var productsWithCategories = from p in _context.Products
                             join c in _context.Categories on p.CategoryId equals c.Id
                             where c.Id == targetCategoryId
                             select new ProductCategoryDto
                             {
                                 ProductName = p.ProductName,
                                 CategoryName = c.CategoryName,
                                 Price = p.Price
                             };
var result = productsWithCategories.ToList();

LINQ UNION示例

var highPriceProducts = _context.Products.Where(p => p.Price > 200);
var zeroStockProducts = _context.Products.Where(p => p.Stock == 0);
var combinedProducts = highPriceProducts.Union(zeroStockProducts).ToList();

用UnionAll方法对应SQL的UNION ALL,不会对结果去重。

关键注意事项

  • 若用DTO接收结果,需确保DTO属性名与SQL查询的列名一致,或通过[Column]特性手动映射。
  • 原生SQL查询必须参数化,杜绝硬编码参数引发的注入风险。
  • 超复杂查询(多表关联+聚合)优先用原生SQL,常规关联/合并逻辑推荐LINQ,兼顾可维护性与类型安全。

内容的提问来源于stack exchange,提问作者Sonia Tyagi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 12:35:12