我有一个带有两个 TableAdapter(一对多关系)的类型化数据集,它是使用 Visual Studio 2010 的配置向导创建的。子表的FK采用级联。它是应用程序的一小部分,用于跟踪组(父表)和组成员(子表)。
我可以很好地将新元组插入到组表中,但是当我尝试将新元组插入到成员表中时,当 FK 基于我刚刚插入到组表中的组时,就会出现问题。您可以在以下代码片段中看到问题
GroupsDataSet.GroupsRow addedGroup = this.groupsDataSet.Groups.AddGroupsRow(groupName, this.type);
this.groupsDataSet.Members.AddMembersRow(memberName, addedGroup);
this.groupsTableAdapter.Update(this.GroupsDataSet.Groups);
this.membersTableAdapter.Update(this.GroupsDataSet.Members);
当我将新行插入组表(父)时,addedGroup.id 返回的 PK id 为 -1,因此成员表(子)插入似乎正在尝试插入新行groupId = -1 的行不存在并且引发错误。添加新组(父组)然后立即添加与新添加的组关联的新成员(子组)的正确方法是什么?
I have a typed DataSet with two TableAdapters (1 to many relationship) that was created using visual studio 2010's Configuration Wizard. The child table's FK uses cascading. It is a small part of an application that keeps track of groups (parent table) and group members (child table).
I can insert new tuples into the Groups table fine but the problem occurs when I am trying to insert new tuples into the Members table when the FK is based on a group that I just inserted into the group table. You can see the problem in the following code snippet
GroupsDataSet.GroupsRow addedGroup = this.groupsDataSet.Groups.AddGroupsRow(groupName, this.type);
this.groupsDataSet.Members.AddMembersRow(memberName, addedGroup);
this.groupsTableAdapter.Update(this.GroupsDataSet.Groups);
this.membersTableAdapter.Update(this.GroupsDataSet.Members);
When I insert a new row into the Group table (parent) the PK id returned by addedGroup.id is -1 so it seems that Members table (child) insertion is trying to insert a new row with groupId = -1 which does not exist and is throwing the error. What is the correct way to add a new Group (parent) and then immediately add a new Member (child) that is associated with the newly added Group?
发布评论
评论(1)
我认为您遇到的问题是,在更新之前,ID 不会被填充。因此,您需要将语句的顺序更改为:
还需要检查插入时刷新设置。如果您查看此链接中的图 3:(我假设 SQL Server 是数据库。)
http://blogs.msdn.com/b/vsdata/archive/2009/09/14/refresh-the-primary-key-identity-column-during-insert-operation.aspx
I think the problem that you have is the ID won't be filled until you update. So you need to change the order of your statements to:
There is also a Refresh on insert setting that needs to be checked. If you look at Figure 3 in this link: (I am assuming SQL Server is the db.)
http://blogs.msdn.com/b/vsdata/archive/2009/09/14/refresh-the-primary-key-identity-column-during-insert-operation.aspx