Take the following EF based code:
var newItem = context.Items.CreateObject();
newItem.ID = Guid.NewGuid();
newItem.Na开发者_开发技巧me = "Some text";
context.Items.AddObject(newItem);
int count = context.Items.Count();
What would cause the count to return zero in this circumstance?
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();
@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();
精彩评论