Windowsフォームアプリにチェックリストボックスがあり、ユーザーは1つ以上のセキュリティグループを選択したユーザーに割り当てることができます。
WCF Data Servicesを使用すると、問題なくボックスにデータを入力できます。ただし、ユーザーがボックス内の選択を変更してそれらの変更を保存しようとすると、問題が発生します。
これが私の論理を説明するコメント付きのコードです。
private void ProcessSecurityGroupSelection_Original()
{
//Get a reference to the selected user, including the associated SecurityGroups.
var user = _ctx.Users
.AddQueryOption("$filter", "UserID eq " + ((DataService.User)lstUsers.SelectedItem).UserID)
.AddQueryOption("$expand", "SecurityGroups")
.First();
//Remove all the SecurityGroups so we can replace them.
user.SecurityGroups.Clear();
foreach (var selectedGroup in lstSecurityGroups.CheckedItems)
{
//Loop through the selected SecurityGroups, linking and adding each SecurityGroup to the User object.
var securityGroup = (from sg in _ctx.SecurityGroups
where sg.SecurityGroupID == ((DataService.SecurityGroup)selectedGroup).SecurityGroupID
select sg).First();
_ctx.AddLink(user, "SecurityGroups", securityGroup);
user.SecurityGroups.Add(securityGroup);
}
_ctx.UpdateObject(user);
_ctx.SaveChanges();
}
以前に選択されたSecurityGroupのAddLinkメソッドにコードがヒットすると、「コンテキストはすでに関係を追跡しています」というエラーが表示されます。Clear()メソッドがコンテキスト内のリンクを削除するようには見えません。
既存のリンクを削除するにはどうすればよいですか、またはこれにすべて間違ってアプローチしていますか?