我是 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/