我有兩個類Contact
和ContactField
如下。當ContactField
被添加到Contact
時,我希望自動分配SortOrder
到ContactField
。我是否需要繼承DbSet並自定義Add
方法?如何實現它?如何觀察DbSet的添加動作<T>?
public class Foo {
private MyDbContext _db = new MyDbContext();
public void HelloWorld() {
Contact contact = ....; //< A contact from database.
ContactField field = ....; ///< A new field
.... ///< assign other properties into this `field`
field.FieldType = FieldType.Phone;
// How to automatically update `SortOrder`
// when adding field into `ContactFields`
contact.ContactFields.Add(field);
_db.SaveChanges();
}
}
public class Contact {
public long ContactID { get; set; }
public string DisplayName { get; set; }
public string DisplayCompany { get; set; }
public DateTime CreatedTime { get; set; }
public DateTime ModifiedTime { get; set; }
// Original codes
//public virtual ICollection<ContactField> ContactFields { get; set; }
public virtual MyList<ContactField> ContactFields { get; set; }
}
public class ContactField {
public long ContactFieldID { get; set; }
public int SortOrder { get; set; }
public int FieldType { get; set; }
public string Value { get; set; }
public string Label { get; set; }
[Column("ContactID")]
public int ContactID { get; set; }
public virtual Contact Contact { get; set; }
}
編輯: 我發現我需要的是監測ICollection<ContactField> ContactFields
的變化。而List<T>
是ICollection<T>
的實現。因此,我創建了一個自定義MyList
,並要求它通知容器的變化MyList
。我會在稍後測試它的有效性。
public class MyList<TEntity> : List<TEntity> {
public delegate OnAddHandler(object sender, TEntity entry);
public event OnAddHandler OnAddEvent;
public new void Add(TEntity entity) {
OnAddEvent(this, entity);
base.Add(entity);
}
}
如果'Contact'沒有保存到'_db',我可以觀察ICollection ContactFields'的Add'動作嗎? –
AechoLiu
2012-03-03 06:30:05
謝謝你的這種做法。我編輯了我的問題。 – AechoLiu 2012-03-03 09:19:21
請記住,訪問'.Local'會將數據庫中的整個表加載到內存中。即使是中等大小的桌子,這也是一個巨大的性能影響! – Breeze 2017-04-05 06:20:55