存根通常只对以下情况有效1-*
关系。*-*
人际关系带来了一系列不同的挑战。
也就是说,当你连接两端时 - 不像1-*
- 你仍然不知道这种关系是否已经存在。
所以这意味着这段代码:
if (issue.Scopes.Contains(thisScope))
可能每次都会返回 false。
我要做的是这样的:
edmx.Issues.Attach(issue);
UpdateModel(issue);
// or ctx.LoadProperty(issue, "Scopes") if it is a POCO class.
issue.Scopes.Load(); // hit the database to load the current state.
现在您需要找出需要从问题范围中添加和删除的内容。
您可以通过根据 ID 进行比较来做到这一点。
即,如果您有一组与该问题相关的范围 ID (relatedScopes)
然后这段代码计算出要添加什么和要删除什么。
int[] toAdd = relatedScopes.Except(issue.Scopes.Select(s => s.ID)).ToArray();
int[] toRemove = issue.Scopes.Select(s => s.ID).Except(relatedScopes).ToArray();
现在对于 toAdd 你这样做:
foreach(int id in toAdd)
{
var scope = new Scope{Id = id};
edmx.Scopes.Attach(scope);
issue.Scopes.Add(scope);
}
对于每个范围,您需要删除
foreach(int id in toRemove)
{
issue.Scopes.Remove(issue.Scopes.Single(s => s.ID == id));
}
现在应该建立正确的关系。
希望这可以帮助
Alex http://twitter.com/adjames
微软