-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathManyToManyPropertyConstraint.cs
71 lines (61 loc) · 2.25 KB
/
ManyToManyPropertyConstraint.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using LazyEntityGraph.Core.Extensions;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
namespace LazyEntityGraph.Core.Constraints
{
public class ManyToManyPropertyConstraint<THost, TProperty> : IPropertyConstraint<THost, ICollection<TProperty>>
where THost : class
where TProperty : class
{
private readonly PropertyInfo _inverse;
public ManyToManyPropertyConstraint(PropertyInfo propInfo, PropertyInfo inverse)
{
PropInfo = propInfo;
_inverse = inverse;
}
public void Rebind(THost host, ICollection<TProperty> nullCollection, ICollection<TProperty> collection)
{
var lazyCollection = collection as LazyEntityCollection<TProperty>;
if (lazyCollection != null)
{
lazyCollection.ItemAdded += x => CollectionProperty.Add(x, _inverse, host);
lazyCollection.ItemRemoved += x => CollectionProperty.Remove(x, _inverse, host);
}
foreach (var x in collection)
{
CollectionProperty.Add(x, _inverse, host);
}
}
public PropertyInfo PropInfo { get; }
#region Equality
protected bool Equals(ManyToManyPropertyConstraint<THost, TProperty> other)
{
return _inverse.PropertyEquals(other._inverse) && PropInfo.PropertyEquals(other.PropInfo);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (obj.GetType() != GetType())
return false;
return Equals((ManyToManyPropertyConstraint<THost, TProperty>)obj);
}
public override int GetHashCode()
{
unchecked
{
return ((_inverse != null ? _inverse.GetHashCode() : 0) * 397) ^
(PropInfo != null ? PropInfo.GetHashCode() : 0);
}
}
#endregion
public override string ToString()
{
return $"{typeof(THost).Name}.{PropInfo.Name} *..* {typeof(TProperty).Name}.{_inverse.Name}";
}
}
}