帮我转换这个SQL查询到LINQ

时间:2010-03-06 14:53:34

标签: linq linq-to-sql

我正在尝试将此SQL查询转换为LINQ:

SELECT Items.p_Name Product, DiamondCategory.dc_Name Category, Diamond.d_Weight Weight
FROM DiamondCategory
INNER JOIN Diamond ON DiamondCategory.dc_Id = Diamond.dc_Id
INNER JOIN Items ON Diamond.p_Id = Items.p_Id where Items.p_Id = 1

Union没有给出结果:

var qry = (from d in myDatabaseDataSet.Diamond select d.d_Weight).Union
          (from c in myDatabaseDataSet.Items select c.p_Name).Union
          (from e in myDatabaseDataSet.DiamondCategory select e.dc_Name);

2 个答案:

答案 0 :(得分:1)

Union没有做你想要的,你需要一个Join。这是一般答案:

from item in myDatabaseDataSet.Items
  where item.p_Id = 1
join diamond in myDatabaseDataSet.Diamond 
  on diamond.p_Id equals item.p_Id
join category in myDatabaseDataSet.DiamondCategory 
  on diamond.dc_Id equals category.dc_Id
select new 
{ 
  Product = item.p_Name, 
  Weight = diamond.d_Weight, 
  Category = category.dc_Name 
};

编辑:从您的代码中,您似乎正在使用LINQ to SQL。如果是这样,那么这样的事情就足够了,假设你在你提到的表之间有外键约束:

from item in myDatabaseDataSet.Items, 
  diamond in item.Diamonds, 
  category in diamond.DiamondCategory
where item.p_Id = 1
select new 
{ 
  Product = item.p_Name, 
  Weight = diamond.d_Weight, 
  Category = category.dc_Name 
};

答案 1 :(得分:0)

您不应该使用Union

来自MSDN:

Produces the set union of two sequences.

您需要使用Join,其中:

Correlates the elements of two sequences based on matching keys.