是否有任何方法在数据集中的表之间进行关联

本文关键字:之间 关联 集中 数据集 任何 方法 数据 是否 | 更新日期: 2023-09-27 18:12:53

我有一个DataSet与3表Categories, ItemsProducts。我可以单独访问它们。但我想将它们绑定到3个不同的ComboBoxes中,这样,更改类别反映项目,更改项目反映产品。我想这可能是通过创建表之间的关系来实现的。

是否有任何方法在数据集中的表之间进行关联

一堆方法可以使用ADO为这只猫添加皮肤。. NET数据集,但您可以使用DataSet.Relations建立数据表之间的关系。查看MSDN文档获取更多信息。

这里有一个例子,你概述的关系,只采取足够远的路径给你的想法:

var ds = new DataSet();
// Add the Categories table with a CategoryID column, and add a few rows to it.
var categories = ds.Tables.Add("Categories");
var categoryIDColumn = categories.Columns.Add("CategoryID", typeof(int));
categories.Rows.Add(new object[] { 1 });
categories.Rows.Add(new object[] { 2 });
categories.Rows.Add(new object[] { 3 });
// Add the Items table with ItemID & CategoryID (FK) columns, and add a few Categories-relatable rows to it.
var items = ds.Tables.Add("Items");
var itemIDColumn = items.Columns.Add("ItemID", typeof(int));
var itemCategoryIDColumn = items.Columns.Add("CategoryID", typeof(int));
items.Rows.Add(new object[] { 11, 1 });
items.Rows.Add(new object[] { 12, 2 });
items.Rows.Add(new object[] { 13, 3 });
// Add the Products table with ProductID & ItemID (FK) columns, and add a few Items-relatable rows to it.
var products = ds.Tables.Add("Products");
var productIDColumn = products.Columns.Add("ProductID", typeof(int));
var productItemIDColumn = products.Columns.Add("ItemID", typeof(int));
products.Rows.Add(new object[] { 21, 11 });
products.Rows.Add(new object[] { 22, 12 });
products.Rows.Add(new object[] { 23, 13 });
// Add the FK relationships (or data relations as it were).
var categoryItemsRelation = ds.Relations.Add("FK_CategoryItems", categoryIDColumn, itemCategoryIDColumn);
var itemProductsRelation = ds.Relations.Add("FK_ItemProducts", itemIDColumn, productItemIDColumn);
// Run through an example of a selected ID in the categories dropdown.
int selectedCategoryID = 1;
var selectedCategory = categories.Select(String.Format("CategoryID = {0}", selectedCategoryID))[0];
var filteredItems = selectedCategory.GetChildRows(categoryItemsRelation);
Console.WriteLine("selectedCategoryID == {0}", selectedCategoryID);
Console.WriteLine("selectedCategory[categoryIDColumn] == {0}", selectedCategory[categoryIDColumn]);
foreach (var childItem in filteredItems)
{
    Console.WriteLine("filteredItems includes:");
    Console.WriteLine(
            "'t{0} : {1}, {2} : {3}",
            itemIDColumn.ColumnName,
            childItem[itemIDColumn],
            itemCategoryIDColumn.ColumnName,
            childItem[itemCategoryIDColumn]);
}
// ...and so forth.

可以通过Dataset实现。关系参考此并尝试在您的代码中实现

// Define the relationship between Categories and Products.
DataRelation relat = new DataRelation("CatProds",
ds.Tables["Categories"].Columns["CategoryID"],
ds.Tables["Products"].Columns["CategoryID"]);

// Add the relationship to the DataSet.
ds.Relations.Add(relat);