Let\'s say we have two tables with a many-to-many relationship:
public class Left{ /**/ }
public class Right{ /**/ }
public class LeftRight{ /**/ }
Here is a 'little' extension method I wrote to simplify this problem:
public static class EntitySetExtensions
{
public static void UpdateReferences(
this EntitySet refs,
Func fkvalue,
Func fkmaker,
Action fkdelete,
IEnumerable 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 could probably be improved, but it has served me well :)
Example:
Left entity = ...;
IEnumerable rights = ...;
entity.LeftRights.UpdateReferences(
x => x.Right, // gets the value
x => new LeftRight { Right = x }, // make reference
x => { x.Right = null; }, // clear references
rights);
Algorithm description:
Suppose A and B is many-to-many relationship, where AB would be the intermediary table.
This will give you:
class A { EntitySet Bs {get;} }
class B { EntitySet As {get;} }
class AB { B B {get;} A A {get;} }
You now have an object of A, that reference many B's via AB.
I would like to improve this by using Expression instead, so I could 'template' the method better, but it would work the same.