繁体   English   中英

C#-实体框架将新对象添加到ObjectContext

[英]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(),但我将其视为一种解决方法。

缺点:当用户取消操作时,新对象将在数据库中。

用例:“创建人”

  1. 用户选择一个名为“创建人”的菜单项(或按钮或其他按钮)(例如,新用户应出现在GridView控件中-调用SaveChanges())
  2. 用户填写名字,姓氏等。
  3. 但是随后用户发现他不需要创建该人(例如,用户记得他昨天已经创建了该人)
  4. 用户不使用“取消”菜单项(或按钮等)来按“保存”按钮(菜单项或其他;-),因此数据库中将有一个孤儿

其他方法:为了将新人员(尚未提交)添加到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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM