簡體   English   中英

如何使用LINQ連接兩個表?

[英]How to join two tables using LINQ?

我正在嘗試使用mvc4 Web API和linq聯接兩個表。

這是分類表的類代碼。

 public partial class catagory
{
    public int id { get; set; }
    public string cat_name { get; set; }
    public Nullable<int> measure_type { get; set; }
    public Nullable<int> active { get; set; }
    public Nullable<int> parent_cat { get; set; }
    public Nullable<int> display_order { get; set; }
    public string cat_image { get; set; }
}

產品表的類別代碼

public partial class product
{
    public int id { get; set; }
    public string p_name { get; set; }
    public Nullable<int> price { get; set; }
    public Nullable<int> catagory_id { get; set; }
    public Nullable<int> brand_id { get; set; }
    public Nullable<int> active { get; set; }
    public Nullable<int> discount_percent { get; set; }
    public Nullable<int> display_order { get; set; }
    public Nullable<int> color_id { get; set; }
    public Nullable<int> seller_id { get; set; }
    public int selling_price { get; set; }
}

我想加入這兩個表。 這是ProductController.cs文件中的代碼

 public class ProductController : ApiController
{

    public List<product> GetProductByColour(int id)
    {
        var query = (from x in db.products.AsEnumerable()
                     join y in db.catagories.AsEnumerable()
                     on x.id equals y.id
                     where x.id.Equals(id)
                     select new product
                     {
                         id = x.id,
                         p_name = x.p_name,
                         price = x.price,
                         catagory_id = y.id,
                         brand_id = x.brand_id,
                         display_order = y.display_order,

                     }).ToList();
        return query.ToList();
    }

您應該將這兩個表同時連接到products表的catagory_id屬性和category表的Id屬性,因為在您的模式中,只有這一個看起來有效的關系

傳入的variale ID可以是產品ID,類別ID中的任何一個,也可以是color_id。 對我來說,似乎更多的是color_id。

有關linq的更多信息,請點擊此鏈接

public class ProductController : ApiController
    {

        public List<product> GetProductByColour(int id)
        {
            var query = (from x in db.products.AsEnumerable()
                         join y in db.catagories.AsEnumerable()
                         on x.catagory_id equals y.id 
                         where x.id.Equals(id)
                         select new product
                         {
                             id = x.id,
                             p_name = x.p_name,
                             price = x.price,
                             catagory_id = y.id,
                             brand_id = x.brand_id,
                             display_order = y.display_order,

                         }).ToList();
            return query;
        }

暫無
暫無

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

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