c# - EF Core 关系查询

标签 c# asp.net-core entity-framework-core

我是 Entity Framework 的新手,我的表关系看起来有点像这样

public class Customer {
    public int Id { get; set; }
    public string Name { get; set; }

    public List<Product> Products { get; set; }
}

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

    public int CustomerId { get; set; }
    public Customer Customer { get; set; }

}

我想查询 Customer 表并只包含最后创建的产品 MAX(Id)

普通的 SQL 查询看起来像这样

SELECT * 
FROM Customer
INNER JOIN Product ON Customer.Id = Product.CustomerId
WHERE Product.Id = (SELECT MAX(Id) FROM Product WHERE CustomerId = Customers.Id)

我当前的 EF 查询看起来像这样,但它返回所有产品...

List<Customer> customers = _context.Customers
                .Include(c => c.Products)
                .ToList();

我尝试了类似这样的方法,它给了我正确的结果,但是 EF 做了一堆查询,很快我发现这似乎是错误的方法

List<Customer> customers = _context.Customers
                .Select(c => new Customer() {
                    Id = c.Id,
                    Name = c.Name,
                    c.Products = c.Products.Where(d => d.Id == c.Products.Max(max => max.Id)).ToList()
                }).ToList();

我想要一些建议,或者是否有不同的方法来实现它。

最佳答案

看起来下面的查询可以用不同的方式编写

SELECT * 
FROM Customer
INNER JOIN Product ON Customer.Id = Product.CustomerId
WHERE Product.Id = (SELECT MAX(Id) FROM Product WHERE CustomerId = Customers.Id)   

这可以写成

SELECT TOP 1 *
FROM Customer
INNER JOIN Product ON Customer.Id = Product.CustomerId
Order by Product.Id desc

假设客户名称是必需的,上面的查询可以用 LINQ 或使用 EF 编写,如下所示

var customers = _context.Customers.Join(_context.Products, cu => cu.id,
p => p.CustomerId, (cu,p) => new { cu,p})
.Select( c => new { prodId = c.p.Id,customername = c.cu.Name })
.OrderByDescending( c => c.prodId).Take(1);

关于c# - EF Core 关系查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38897978/

相关文章:

c# - 自定义 WPF 中列表框中选择的可视化

c# - ThreadStatic 属性如何工作?

mysql - 通过反射确定泛型 TEntity 的哪些 PropertyInfo 是主键

c# - 将 IdentityUser 关联到 EF Core 中的实体

c# - 以编程方式更改 Monotouch 中的按钮标签

c# - 使用 SSH.NET 在进度栏中显示文件下载进度

asp.net-core - HttpResponse 不包含 Dot Net Core 的 AddHeader 的定义

Websocket 和 Identityserver4 身份验证

c# - 如何处理 asp.net core 中的异常 "Invalid file signature"?

asp.net-mvc - Entity Framework 核心错误: No parameterless constructor defined for this object