我在DataTables
中有两个DataSet
由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;
答案 0 :(得分: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,就可以获得所需的结果。
答案 1 :(得分: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
}