Here is a small extension method I wrote to simplify this problem:
public static class EntitySetExtensions
{
public static void UpdateReferences<FK, FKV>(
this EntitySet<FK> refs,
Func<FK, FKV> fkvalue,
Func<FKV, FK> fkmaker,
Action<FK> fkdelete,
IEnumerable<FKV> values)
where FK : class
where FKV : class
{
var fks = refs.Select(fkvalue).ToList();
var added = values.Except(fks);
var removed = fks.Except(values);
foreach (var add in added)
{
refs.Add(fkmaker(add));
}
foreach (var r in removed)
{
var res = refs.Single(x => fkvalue(x) == r);
refs.Remove(res);
fkdelete(res);
}
}
}
It can probably be improved, but it recommended me well :)
Example:
Left entity = ...;
IEnumerable<Right> rights = ...;
entity.LeftRights.UpdateReferences(
x => x.Right,
x => new LeftRight { Right = x },
x => { x.Right = null; },
rights);
Description of the algorithm:
Suppose A and B are many-to-many relationships, where AB will be an intermediate table.
This will give you:
class A { EntitySet<B> Bs {get;} }
class B { EntitySet<A> As {get;} }
class AB { B B {get;} A A {get;} }
A, B AB.
- B A.Bs 'fkvalue'.
- , .
- , .
- AB "fkmaker".
- .
- 'fkdelete'.
, Expression , "" , .