2012-01-16 55 views
2

我有两个DataTablesDataSet通过DataRelation链接在一起,我试图选择具有值为x的子行的所有父行。DataSet选择其父行包含x值的父行

父表中包含的产品和子表中包含的类别,该产品是英寸

DataSet dsProducts = new DataSet(); 

DataTable dtProducts = new DataTable("products"); 
dtProducts.Columns.Add("entity_id", typeof(int)); 
dtProducts.Columns.Add("sku", typeof(string)); 
dtProducts.Columns.Add("mpn", typeof(string)); 
dtProducts.Columns.Add("brand", typeof(string)); 
dtProducts.Columns.Add("name", typeof(string)); 
dtProducts.Columns.Add("description", typeof(string)); 
dtProducts.Columns.Add("short_description", typeof(string)); 
dtProducts.Columns.Add("image", typeof(string)); 
dtProducts.Columns.Add("weight", typeof(double)); 
dtProducts.Columns.Add("qty", typeof(double)); 
dtProducts.Columns.Add("cost", typeof(double)); 
dtProducts.Columns.Add("price", typeof(double)); 
dtProducts.PrimaryKey = new DataColumn[] { dtProducts.Columns["entity_id"] }; 
dsProducts.Tables.Add(dtProducts); 

DataTable dtCategories = new DataTable("categories"); 
dtCategories.Columns.Add("entity_id", typeof(int)); 
dtCategories.Columns.Add("category_id", typeof(int)); 
dsProducts.Tables.Add(dtCategories); 

dsProducts.Relations.Add(new DataRelation("entity_id", dtProducts.Columns["entity_id"], dtCategories.Columns["entity_id"])); 

编辑

我拼凑这片LINQ的代码工作但似乎没有意义DataRelation

var rows = from prods in dsProducts.Tables["products"].AsEnumerable() 
      join cats in dsProducts.Tables["categories"].AsEnumerable() on prods.Field<int>("entity_id") equals cats.Field<int>("entity_id") 
      where cats.Field<int>("category_id") == id 
      select prods; 
+0

如果您的答案适合您,请随时回答您自己的问题。 – 2012-01-16 21:09:43

+0

它的工作原理,但是在那里已经存在关系时,必须重新创建一个关系似乎有点愚蠢。 – Christian 2012-01-16 21:14:53

回答

1

尝试:

DataRow[] rows = dsProducts.Tables["products"].Select("entity_id=" + id); 

代替:

DataRow[] rows = dsProducts.Tables["products"].Select("Child(entity_id).category_id = " + id); 

因为你已经创建了两个表,公共列“ENTITY_ID”之间的关系,所以只要你ENTITY_ID匹配,你得到你想要的结果。

+0

,它将带回所有具有该entity_id的产品。我寻找只在特定类别产品的行集 – Christian 2012-01-16 18:41:26

0
DataRelation relation = dsProducts.Relations.Add(new DataRelation("entity_id", dtProducts.Columns["entity_id"], dtCategories.Columns["entity_id"])); 

DataRow[] childRows = dsProducts.Tables["categories"].Select("category_id=" + id); 
foreach (DataRow row in childRows) { 
    DataRow[] parentRows = row.GetParentRows(relation); // parentRows[0] should be your parent 
} 
+0

不应该是儿童的类别DataRow [] childRows = dsProducts.Tables [“类别”]“和关系应该是'entity_id' – Christian 2012-01-16 18:58:50

+0

@Christian:你是正确。固定。 – 2012-01-16 20:27:32