[英]C# - Entity Framework add new object to ObjectContext
我正在使用實體框架,SQL和C#。
我有一個名為Client的表,另一個名為clients_phone的表。
我有一個帶有Xtragrid的表單,並使用BindingSource將IQueryable綁定到網格。
myBindingSource = new BindingSource();
myBindingSource.DataSource = clients; //Clients it is the IQueryable<Client>
myBindingSource.DataMember = "clients_phone";
myBindingSource.AllowNew = true;
然后,我想向我的客戶添加一個新的clients_phone。 為此,我創建一個New Client(),然后添加Phone。
clients newclient = objContext.CreateObject<clients>();
newclient.clients_phone = newClients_Phone;
objContext.AddObject("Clients", newclient);
最終,我在ObjectContext中添加了新的clients_phone,但是當我看到Xtragclients_phone時,它不顯示。
任何想法會發生什么??。
謝謝
盧卡斯B是對的。 每當您要添加所有新的Clients和Clients_phone時,都需要調用SaveChanges()方法以將數據持久保存到數據庫中。
是否需要先創建客戶端,然后進行更新以添加更多的client_phone條目或其他內容。 如果您從不調用SaveChanges()方法,則您所做的任何操作都將被保存回數據庫。
您是否嘗試過保存並提交對象?
objContext.SaveChanges(true);
objContext.AcceptAllChanges();
我已經完成了SaveChanges(),但我將其視為一種解決方法。
缺點:當用戶取消操作時,新對象將在數據庫中。
用例:“創建人”
其他方法:為了將新人員(尚未提交)添加到GridView控件中,可以將DataSource設置為“當前人員+新人員”
private object GetBindingList(ObjectSet<Person> contextObjects, Person newObject)
{
List<Person> list = new List<Person>();
list.AddRange(contextObjects);
list.Add(newObject);
return list;
}
用法:
PersonsBindingSource.DataSource = GetBindingList(Context.PersonSet, newPerson);
但這有一個缺點:它僅在第一次使用時有效...因此,您需要執行以下操作:
PersonsBindingSource.DataSource = GetBindingList(Context.PersonSet, newPerson);
Context.PersonSet = Populate with persons from PersonsBindingSource.DataSource // ;-)
但是為什么contextContexts.AddObject(newObject); 不起作用(新項目將不會顯示在GridView中-僅對沒有外鍵指向其他對象的對象會發生此問題)
也僅在調用SaveChanges()時有效 :
PersonsBindingSource.DataSource = Context.PersonSet.Execute(MergeOption.AppendOnly);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.