尝试 1:在创建实体类的 T4 模板中,将 NavigationProperty 更改为:
public string NavigationProperty(NavigationProperty navigationProperty)
{
var endType = _typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType());
return string.Format(
CultureInfo.InvariantCulture,
"{0}\n\n {1} {2} {3}\n {{\n {4}get\n {{\n return _{3}; \n }}\n {5} set\n {{\n _{3}=value; OnSet{3}();\n }}\n }}\n\n {6}",
string.Format(CultureInfo.InvariantCulture, "{0} _{1};",_typeMapper.GetTypeName(navigationProperty.TypeUsage), _code.Escape(navigationProperty)),
AccessibilityAndVirtual(Accessibility.ForProperty(navigationProperty)),
navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType,
_code.Escape(navigationProperty),
_code.SpaceAfter(Accessibility.ForGetter(navigationProperty)),
_code.SpaceAfter(Accessibility.ForSetter(navigationProperty)),
string.Format(CultureInfo.InvariantCulture, "partial void OnSet{0}();", _code.Escape(navigationProperty)));
}
然后添加部分 Entity1 类:
Partial Class Entity1:EntityBase
{
public SpecificObservableCollection<Entity2> Entity2_Observable
{
get;
set;
}
partial void OnSetEntity2()
{
Misc_Observable.Add(Entity2);
}
public class SpecificObservableCollection<T> : ObservableCollection<T>
{
public Action<T> SetValue { get; set; }
protected override void InsertItem(int index, T item)
{
if (item != null)
{
base.InsertItem(index, item);
}
}
protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
base.OnCollectionChanged(e);
if (this.Count>0)
SetValue(this[0]);
}
}
protected override void DoStuffOnAdd()
{
Entity2_Observable = new SpecificObservableCollection<Entity2>();
Entity2_Observable.SetValue = a => _Entity2 = a;
}
}
然后在 EntityBase 中:
public abstract class EntityBase
{
EntityBase()
{
DoStuffOnAdd();
}
protected virtual void DoStuffOnAdd() { }
}
对于 IValueConverter(为了避免在 1:1 关系中添加太多记录)
public class CanAddValueConverter : IValueConverter
{
private Type _T;
private DataGrid _dg;
public void SetValues(DataGrid dg, Type T)
{
_T = T;
_dg = dg;
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
System.Collections.IEnumerable dgIS = value as System.Collections.IEnumerable;
if (_dg != null && dgIS == _dg.ItemsSource)
{
if (_dg.Items.Count > 0)
return _dg.Items.Count <= System.Convert.ToInt32(parameter) && _dg.Items[_dg.Items.Count - 1].GetType() != _T;
else
return true;
}
else
return false;
}
}
然后在 CodeBehind 中,将 DataGrid 分配给 IValueConverter 以及相应的实体类型。