大廈拉吉斯拉夫的答案被忽略到複雜類型由實體框架代碼優先
Entity Framework Code First and Collections of Primitive Types
我試圖給ObservableCollection<T>
有一個額外的輔助特性來簡化持久周圍創建一個包裝類型EfObservableCollection<T>
(當然這解決方案有折衷,但對我的域名來說似乎可行)。
但是,類型EfObservableCollection<T>
的屬性似乎被EF忽略。數據庫中沒有創建適當的列。猜測實施IEnumerable<T>
可能會觸發EF忽略這種類型,我評論說實施沒有改變行爲。
缺少什麼我在這裏?
實體類
public class A
{
[DataMember]
public long Id { get; set; }
[DataMember]
public string Text { get; set; }
// Tags is not persisted
[DataMember]
public EfObservableCollection<string> Tags { get; set; }
}
包裝類
[ComplexType]
public class EfObservableCollection<T> : IEnumerable<T>
{
const string VALUE_SEPARATOR = "\x8"; // Backspace character. Unlikely to be actually entered by a user. Assumes ASCII or UTF-8.
readonly string[] VALUE_SEPARATORS = new string[] { VALUE_SEPARATOR };
[NotMapped]
protected ObservableCollection<T> Collection { get; private set; }
public EfObservableCollection()
{
Collection = new ObservableCollection<T>();
}
[DataMember]
public string PersistHelper
{
get
{
string serializedValue = string.Join(VALUE_SEPARATOR, Collection.ToArray());
return serializedValue;
}
set
{
Collection.Clear();
string[] serializedValues = value.Split(VALUE_SEPARATORS, StringSplitOptions.None);
foreach (string serializedValue in serializedValues)
{
Collection.Add((T)Convert.ChangeType(serializedValue, typeof(T))); // T must implement IConvertable, else a runtime exception.
}
}
}
public void Add(T item)
{
Collection.Add(item);
}
IEnumerator<T> GetEnumerator()
{
return Collection.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}