使用lambda表达式在Linq中连接表

本文关键字:连接 Linq lambda 表达式 使用 | 更新日期: 2023-09-27 18:11:57

我正在使用实体框架。我必须应用两个表的连接,但我想要的是,如果有一个表Category,列categoryid作为整数数据类型的外键,另一个表Products,列id作为主键,也是整数数据类型。

现在我只需要选择Products表中包含Category表中的id的记录。

这是我的代码:

string categoryid= "10,11,12";
datalist.DataSource = (from p in objCategory
                             join q in objProducts on p.categoryid.contains(q.id)
                             select new
                             {
                                 p.FilePath,
                                 p.ItemName,
                                 p.Description,
                                 q.image_url,
                                 q.name,
                                 q.price
                             }).ToList();

使用lambda表达式在Linq中连接表

你可以这样写:

List<int> categoryIds = new List<int>(){ 10, 11, 12 };
datalist.DataSource = (from c in objCategory
                       join p in objProducts 
                       on c.categoryid equals p.categoryid
                       where categoryIds.Contains(c.categoryid)
                       select new
                       {
                           c.FilePath,
                           c.ItemName,
                           c.Description,
                           p.image_url,
                           p.name,
                           p.price
                       }).ToList();

与其将所有数据读取到内存中,还不如创建导航属性并通过这些属性读取数据。在这种情况下,所有连接都将在数据库中工作,您将只从数据库中获得过滤后的数据。解决方案就像

class Category
{
  public int CategoryId { get; set; }
  public string Description{ get; set; }
  public string FilePath {get;set;}
  public string ItemName {get;set;}
  public virtual ICollection<Product> Product{ get; set; } 
}
class Product
{
   public int ProductId { get; set; }
   public string name{ get; set; }
   public int CategoryId { get; set; }
   public string Product.image_url {get;set;}
   public int price {get;set;}
   public virtual Category Category{ get; set; }
}

现在只需调用以下查询

datalist.DataSource = (from p in objCategory.Include("Product")                            
                         select new
                         {
                             p.FilePath,
                             p.ItemName,
                             p.Description,
                             p.Product.image_url,
                             p.Product.name,
                             p.Product.price
                         }).ToList();