我有两个名为 Contact
的类和 ContactField
如下。当 ContactField
添加到 Contact
, 希望赋值SortOrder
至 ContactField
自动地。我是否需要继承 DbSet 并自定义 Add
方法 ?如何实现?
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);
}
}
最佳答案
DbSet 有一个 Local ObservableCollection
属性。您可以订阅 CollectionChanged
事件并在那里更新排序顺序。
public class Foo {
private MyDbContext _db = new MyDbContext();
public void HelloWorld() {
_db.Contacts.Local.CollectionChanged += ContactsChanged;
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 void ContactsChanged(object sender, NotifyCollectionChangedEventArgs args) {
if (args.Action == NotifyCollectionChangedAction.Add)
{
// sort
}
}
}
关于c# - 如何观察DbSet<T>的Add Action ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9543208/