简体   繁体   English

ObjectContext没有添加实体

[英]ObjectContext not adding an entity

I'm adding an entity to the object context like this 我在这样的对象上下文中添加一个实体

public partial class MyEntities : ObjectContext
.
.
.

In a different class I've the following code 在另一个类中,我有以下代码

using (MyEntities dbContext = new MyEntities())
{
  Info x = new Info();

  dbContext.AddToInfo(x);
}

However when I check the entities in Info in 'dbContext' after adding 'x' to it the watch say that dbContext.Info 'Enumeration yielded no results'. 但是,当我在添加了“ x”后在“ dbContext”中检查Info中的实体时,手表会说dbContext.Info“枚举未产生任何结果”。

Here's a screenshot of the Watch window 这是“监视”窗口的屏幕截图

VS观察窗

Why is this happening? 为什么会这样呢?

Try : 尝试:

using (MyEntities dbContext = new MyEntities())
{
  Info x = new Info();

  dbContext.YourTableObjectSet.AddObject(x);
}

YourTableObjectSet is the name of the ObjectSet that represents your table. YourTableObjectSet是代表您的表的ObjectSet的名称。

Then you add a new entity, it is only present in the ObjectStateManager. 然后,您添加一个新实体,该实体仅存在于ObjectStateManager中。 For your entity to present in the ObjectSet, you need to call the dbContext.SaveChanges. 为了使您的实体出现在ObjectSet中,您需要调用dbContext.SaveChanges。

If you want to be able to enumerate through all your Entities need to query the ObjectSet and the ObjectStateManager. 如果您希望能够枚举所有实体,则需要查询ObjectSet和ObjectStateManager。

dbContext.Infos.Union(dbContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added).Select(e=> e.Entity).OfType<Info>)

(the syntax may be wrong, I convert the code from vb.net from memory only) (语法可能是错误的,我仅从内存中转换vb.net中的代码)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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