我对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();
我想提出一些建议,或者是否有不同的方法可以使其发挥作用。
答案 0 :(得分:2)
看起来下面的查询可以用不同的方式编写
f("z", "b")
f("a", "b", 1, "ff");
f("a", "b", "ff", "hic");
f("a", "b", "ff", "no-hic");
这可以写成
SELECT *
FROM Customer
INNER JOIN Product ON Customer.Id = Product.CustomerId
WHERE Product.Id = (SELECT MAX(Id) FROM Product WHERE CustomerId = Customers.Id)
假设客户名称是必需的,上述查询可以用LINQ编写或使用EF编写如下
SELECT TOP 1 *
FROM Customer
INNER JOIN Product ON Customer.Id = Product.CustomerId
Order by Product.Id desc
答案 1 :(得分:0)
如果您已配置导航属性1-n,我建议您使用:
var customers = _context.Customers
.SelectMany(c => c.Products, (c, p) => new { c, p })
.Select(b => new { prodId = b.p.Id, customername = b.c.Name })
.OrderByDescending(c => c.prodId).Take(1);
对我来说更清晰,使用多个嵌套联接看起来更好。
答案 2 :(得分:-1)
有两种语法支持.NET(LINQ)在Entity Framework中进行查询
如果你想使用与SQL查询类似的东西使用“查询语法”,只需使用as Query syntax
from cus in customers select cust;
customers.where(s=>s.name == "ali").toList;
使用var
保存结果。
我想你很擅长使用lambda expressions