[英]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.