我在使用 EF 时遇到了类似的问题,我想将查询返回的列表转换为类属性的等效字典。非常类似于你想让LeaveEntitlementDetails 被LeveEntitlementStore 包裹的方式
例如:
class A
{
[NotMapped()]
public Dictionary<int, DataType> Data {get; set}
//refers to Data.Values
public ICollection<DataType> DataAsList {get; set}
}
我希望 DataAsList 基本上包裹 Data.Values
经过大量的试验和错误,我发现 EF,对于集合(可能更多)通过 getter 的返回值(而不是 setter)改变。
IE。从我的数据库初始化时:
var pollquery=From bb In DBM.Dbi.DataTable.Includes("DataAsList")
Where bb.Id = id
Select bb;
ClassA objInstance = pollquery.First();
ClassA.DataAsList 的 setter 从未被调用,但 getter 是在 EF 内部构造我的对象期间进行的。结论:EF 正在使用从属性 ClassA.DataAsList 的 getter 检索到的引用,并将对象添加到它。
所以我将 DataAsList 的 getter 返回值包装在 ObservableCollection 中,并为 CollectionChanged 参数添加了一个处理程序,果然,我的 CollectionChanged 处理程序正在接收 .Add 调用。
这是我的hackaround-workaround:
class A : INotifyPropertyChanged
{
//So we can let EF know a complex property has changed
public event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged;
//here's our actual data, rather than an auto property, we use an explicit member definition so we can call PropertyChanged when Data is changed
private Dictionary<int, DataType> m_data = new Dictionary<int, DataType>();
//not mapped property as it's not mapped to a column in EF DB
[NotMapped()]
public Dictionary<int, DataType> Data {
get { return m_data; }
set {
m_data = value;
//now call PropertyChanged for our Front (so EF will know it's been changed)
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs("DataAsList"));
}
}
}
//this is our front for the data, that we use in EF to map data to
[DebuggerHidden()]
public ICollection<DataType> DataAsList {
get {
ObservableCollection<DataType> ob = new ObservableCollection<DataType>(Data.Values());
ob.CollectionChanged += Handles_entryListChanged;
return ob;
}
set {
//clear any existing data, as EF is trying to set the collections value
Data.Clear();
//this is how, in my circumstance, i converted my object into the dictionary from an internal obj.Id property'
foreach (DataType entry in value) {
entryions.Add(entry.id, entry);
}
}
}
//This will now catch wind of any changes EF tries to make to our DataAsList property
public void Handles_entryListChanged(object sender, NotifyCollectionChangedEventArgs e)
{
//Debugger.Break()
switch (e.Action) {
case NotifyCollectionChangedAction.Add:
foreach (DataType entry in e.NewItems) {
m_data.Add(entry.Id, entry);
}
break;
default:
Debugger.Break();
break;
}
}
}
注意魔法是:
public ICollection<DataType> DataAsList {
get {
ObservableCollection<DataType> ob = new ObservableCollection<DataType>(Data.Values());
ob.CollectionChanged += Handles_entryListChanged;
return ob;
}
我们订阅对返回列表所做的任何更改,Handles_entryListChanged 我们处理并基本上复制所做的任何更改。