[英]LINQ query on entities with join returning items by category
我正在使用实体框架核心。 我有以下实体:
public class Category {
public long Id { get; set; }
public string Name { get; set; }
}
public class Product {
public long Id { get; set; }
public long CategoryId { get; set; }
public string Name { get; set; }
}
我想要一个分组,其中我的键是我的类别,并且我有一个产品列表。 我想对数据库运行单个查询来执行此操作。
var data = context.Categories
.Join(
Products,
c => c.Id,
p => p.CategoryId,
(c, p) => new {
Category = c,
Product = p
}
)
.ToList();
这会运行我想要的查询,并且似乎会生成一个包含匿名 object 的列表,该列表具有类别和产品。 如果我然后执行以下操作,它会做我想要的:
var grouped = data.GroupBy(x => new { x.Category });
键很好,但值列表似乎重复了类别。 有没有办法做到这一点,所以我有一个 Key 是 Category 然后值是 Product 对象的列表? 更喜欢方法语法,但在这一点上,如果有人能得到我,我希望能弄清楚查询语法。
尝试以下操作:
class Program
{
static void Main(string[] args)
{
Context context = new Context();
var results = (from c in context.Categories
join p in context.Products on c.Id equals p.CategoryId
select new { category = c, product = p })
.GroupBy(x => x.category.Id)
.ToList();
}
}
public class Context
{
public List<Category> Categories { get; set; }
public List<Product> Products { get; set; }
}
public class Category
{
public long Id { get; set; }
public string Name { get; set; }
}
public class Product
{
public long Id { get; set; }
public long CategoryId { get; set; }
public string Name { get; set; }
}
这将是一个按类别分组的产品列表
public class Category {
public long Id { get; set; }
public string Name { get; set; }
}
public class Product {
public long Id { get; set; }
public long CategoryId { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
ICollection<Category> categories = new Collection<Category>(new List<Category>());
ICollection<Product> products = new Collection<Product>(new List<Product>());
var data = categories
.Join(
products,
c => c.Id,
p => p.CategoryId,
(c, p) => new {
Category = c,
Product = p
}
)
.ToList();
var grouped = data.GroupBy(o => o.Category, o => o.Product);
}
}
正确的解决方案是这样的:
var result = (from p in context.Products
join c in context.Categories
on p.CategoryId equals c.Id
select new
{
Product = p,
Category = c
})
.ToList() // because still grouping object is not supported in EF Core we have to materialize first and then do our grouping
.GroupBy(g => g.Category, g => g.Product)
.ToDictionary(p => p.Key, p => p.ToList());
这就是我最终解决它的方式:
var grouped = data
.GroupBy(x => new { x.Category })
.Select(x => new {
Category = x.Key.Category,
Products = x.ToList().Select(x => x.Product).ToList()
});;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.