开发者

Entities not getting added

开发者 https://www.devze.com 2023-03-05 10:23 出处:网络
Take the following EF based code: var newItem = context.Items.CreateObject(); newItem.ID = Guid.NewGuid();

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();
0

精彩评论

暂无评论...
验证码 换一张
取 消