我正在尝试使用mvc4 web API和linq加入两个表。
这是catagory表的类代码。
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; }
}
产品表类的代码
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();
}
我想加入这两张桌子。这是ProductController.cs文件中的代码
{{1}}
答案 0 :(得分:1)
您应该在产品表catagory_id属性和类别表Id属性上加入这两个表,因为在您的模式中只有这一个看起来有效的关系
传入的变量ID可以是产品ID,类别ID中的任何一个,也可以是color_id。对我而言,似乎更多color_id。
有关linq的更多信息,请按照此link
进行操作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;
}