简体   繁体   中英

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'.

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.

Then you add a new entity, it is only present in the ObjectStateManager. For your entity to present in the ObjectSet, you need to call the dbContext.SaveChanges.

If you want to be able to enumerate through all your Entities need to query the ObjectSet and the 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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