从数据库填充嵌套集合

时间:2008-12-23 21:30:11

标签: .net vb.net

我有以下3个班级

Book
Product
SpecialOptions

书籍很多,每本书都有很多产品。同样在产品中有许多SpecialOptions。这三个类中的每一个都有其他属性,因此每个类都有以下接口

Public Interface IBook
   Private ProductList() as collection (of Products)
   Private Somethingelse() as String
End Interface

Public Interface IProduct
   Private SpecialOptionsList() as collection (of SpecialOptions)
   Private Somethingelse() as String
End Interface

Public Interface ISpecialOptions
   Private SpecialOptionsProperty() as String
End Interface

我想创建一个Books集合,其中包含每个产品,并且当我从数据库中提取数据时,在每个产品下我都需要关联的SpecialOptions。我无法决定哪种方式最好。

我有两种方法。要么我从上到下,要么从下到上。这意味着,我从一本书开始,然后填写产品信息,然后为每个产品填写详细信息。或者我可以先获取详细信息,然后将它们添加到相应的产品中,然后再将产品再次添加到书籍中。这些都不是很有吸引力。

另外,因为我在校对时向自己建议,这是我需要捕捉实际关系的结构,所以用不同的结构重构问题是行不通的。

2 个答案:

答案 0 :(得分:1)

你说

  

...从一本书开始,然后填写   然后为产品信息   每个产品都填写了   详细信息......

我会从这本书开始,然后深入研究。这样您就可以只过滤必要的信息。

我希望能回答你的问题。

答案 1 :(得分:1)

有几种方法可以解决这个问题:

加载所有书籍,然后在创建每个书籍对象时,加载所有产品,然后在创建每个Product对象时,加载特殊选项。这将导致对数据库的大量查询,但是很简单并且使DB Sprocs保持简单。 Psudo代码:

foreach bookR in GetBooks
    Add a new book to the book collection
    foreach product in GetProductByBook
        Add a new product to the book's product collection
        foreach option in GetOptionByProduct
            Add a new option to the product option collection

在一个Sproc中加载所有书籍,所有书籍产品和所有产品选项,返回3个结果集。然后首先创建所有图书,然后通过在图书集中找到正确的图书并将其添加到那里来创建您的产品。同样适用于您的产品。 Psudo代码:

foreach bookR in GetResultSet1
    Add a new book to the book collection
foreach productR in GetResultSet2
    Find the correct book in book collection
    Add a new product to the book's product collection
foreach option in GetResultSet3
    Find the correct book in the book collection
    Find the correct product in the book's product collection
    Add a new option to the product option collection

将一个结果集中的所有数据恢复(LINQ-to-Sql以这种方式执行)。将所有三个表连接在一起并返回一个结果集。遍历每一行,检查是否存在与该行匹配的书籍(如果没有创建),然后检查该书籍上的产品是否存在(如果不存在)。 Psudo代码:

results = GetResultSet
foreach result in results
    get the book for matching result book id
    if the book does not exist, create it from result
    get the product on the book for the matching result product id
    if the product does not exist, create it from result
    etc
相关问题