簡體   English   中英

使用Lambda表達式在Linq中聯接表

[英]Join Tables in Linq using lambda expression

我正在使用實體框架。 我必須應用兩個表的聯接,但是如果有一個表Category具有列categoryid作為外鍵(其是整數數據類型)和另一個表Products具有列id作為主鍵(也具有整數數據類型),我想要什么。

現在,我只需要從Products表中選擇id包含在Category表中的那些記錄。

這是我的代碼:

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();

您可以這樣:

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM