Devin Goble
Devin Goble

Reputation: 2857

Entities not getting added

Take the following EF based code:

var newItem = context.Items.CreateObject();
newItem.ID = Guid.NewGuid();
newItem.Name = "Some text";
context.Items.AddObject(newItem);
int count = context.Items.Count();

What would cause the count to return zero in this circumstance?

Upvotes: 2

Views: 82

Answers (2)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364259

@John is right. I'm just adding why? You didn't call SaveChanges before calling Count. Count is extension method from IQueryable and it makes query to the database and return count of stored entities. Unit you call SaveChanges the entity is not stored.

If you want number of pending inserts you can call:

var count = context.ObjectStateManager
                   .GetObjectStateEntries(EntityState.Added)
                   .Select(e => e.Entity)
                   .OfType<Item>()
                   .Count();

Upvotes: 5

John Hartsock
John Hartsock

Reputation: 86872

You forgot

context.SaveChanges();

It should look like this

var newItem = context.Items.CreateObject();
newItem.ID = Guid.NewGuid();
newItem.Name = "Some text";
context.Items.AddObject(newItem);
context.SaveChanges();   
int count = context.Items.Count();

Upvotes: 8

Related Questions