2

我有两个DataTables通过 aDataSet链接在一起DataRelation,我正在尝试选择所有具有值为 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;
4

2 回答 2

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 匹配,您就会得到您想要的结果。

于 2012-01-16T18:32:44.387 回答
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
}
于 2012-01-16T18:52:09.027 回答