代码之家  ›  专栏  ›  技术社区  ›  Mephisztoe

ParentRelations在生成的数据集中不起作用?

  •  0
  • Mephisztoe  · 技术社区  · 16 年前

    我创建了两个表:

    出版社

    • PK、PublisherId、int、非null、标识+1
    • PublisherName,varchar(50),不为空

    产品

    • PK、ProductId、int、非null、标识+1
    • ProductName,varchar(50),不能为空
    • PublisherId,int,不能为空

    然后我创建了一个外键约束 FK__产品__出版商 在连接PublisherId的表之间。

    这样,我希望支持每个发布商都有一个发布商的产品,而每个发布商可以有多个产品。就这么简单。

    现在,我用C#创建了一个控制台项目,添加了一个类型化数据集和两个TableAdapter。一个指向出版商,一个指向产品。DataSet设计器根据从SQL Server获取的内容自动添加关系。

    它还会自动生成属性,允许我访问所选产品的发布者以及所选发布者的所有产品。

    这是我的测试代码:

    ProductTableAdapter adapter = new ProductTableAdapter();
    
    foreach (ProductRow product in adapter.GetData())
    {
        Console.WriteLine(product.PublisherRow.PublisherName);
    }
    

    但是,这不起作用。使用生成的代码,属性PublisherRow看起来像这样:

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    public LanguageRow PublisherRow {
        get {
            return ((PublisherRow)(this.GetParentRow(this.Table.ParentRelations["FK_Product_Publisher"])));
        }
        set {
            this.SetParentRow(value, this.Table.ParentRelations["FK_Product_Publisher"]);
        }
    }
    

    这个。表。ParentRelations不包含该关系。它为null,访问它会导致NullReferenceException。

    我在这里做错了什么?

    1 回复  |  直到 16 年前
        1
  •  2
  •   Mephisztoe    16 年前

    回复我自己的帖子似乎有点奇怪。这有点像和自己说话。然而,我找到了一个解决方案,由于这个问题似乎很常见,我把它贴在这里。

    仅仅使用TableAdapter获取数据并不能从数据库中检索到正确的关系。关系的初始化发生在数据集类内(即从数据集'c'调用的InitClass方法):

    public DbDataSet() {
        this.BeginInit();
        this.InitClass();
        ...
        this.EndInit();
    }
    

    相应的生成的InitClass方法如下:

    private void InitClass() {
        ...
        this.relationFK_Product_Publisher= new global::System.Data.DataRelation("FK_Product_Publisher", new global::System.Data.DataColumn[] { this.tableProduct.PublisherIdColumn}, new global::System.Data.DataColumn[] { this.tablePublisher.PublisherIdColumn}, false);
        this.Relations.Add(this.relationFK_Product_Publisher);
    }
    

    这就是为什么你需要实例化数据集类本身,并使用fill方法填充你的表类,如下所示:

    DbDataSet ds = new DbDataSet();    
    
    ProductTableAdapter productAdapter = new ProductTableAdapter();            
    productAdapter.Fill(ds.Product);
    
    PublisherTableAdapter publisherAdapter = new PublisherTableAdapter();
    publisherAdapter.Fill(ds.Publisher);
    
    foreach (ProductRow product in ds.Product)
    {                
        Console.WriteLine(product.PublisherRow.PublisherName);
    }