开发者

Inserting new tuples into a 1 to many relationship tables using c# DataSet

I have a 开发者_如何学JAVAtyped 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?


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:

GroupsDataSet.GroupsRow addedGroup = this.groupsDataSet.Groups.AddGroupsRow(groupName,      this.type);
this.groupsTableAdapter.Update(this.GroupsDataSet.Groups);
this.groupsDataSet.Members.AddMembersRow(memberName, addedGroup);
this.membersTableAdapter.Update(this.GroupsDataSet.Members);

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜