Make sure the object is already in the context of the Entity Framework

I am having a problem when using EF4 when I try to check if an object is already in the Entity Framework context.

I have this code below

var entityName = Entity4Test + Guid.NewGuid(); using( var ctx = new EnviroDataContext() ) { var etc = new Entity { Name = entityName }; ctx.Entity.AddObject( etc ); var q = from p in ctx.Entity where p.Name == entityName select p; // Why 'q.ToList().Count == 0'? ctx.SaveChanges(); } 

My question is, why did my search after insertion go blank?

I know that the data is saved after "SaveChanges", but what if I need to "query" the memory data of the entity.

Question extension

I have a business rule that adds 1 element A, starts the insertion of other objects B. The problem is that I have a verification rule that when inserting B, t A already exists.

Since all these actions are performed before "SaveChanges", I get an error message that EntityA does not exist.

Another case , I have a Name field unique to the table. If I try to run AddEntityName ("bla") twice and then "SaveChanges", I get an exception from DB [Unique constraints] even after passing my check for insertion, which guarantees the uniqueness of the name.

Anyone have an idea?

+6
entity-framework entity-framework-4
source share
2 answers

When you execute .AddObject , it adds it to the internal EF "memory" graph in the pending "Added" state.

Only after ctx.SaveChanges() executed will the changes be saved in the underlying repository.

The request you requested contradicts the database, and this change has not yet been saved.

So, if you completed your request after ctx.SaveChanges() executed, the count would be as expected.

On the side of the note, if you want to see if an object exists on the chart (for example, before "Attach"), read ObjectStateManager.TryGetObjectStateEntry .

+9
source share

I did not use EF4, but used the previous version, so I do not know if they have a different expectation in EF4. It looks like you are trying to search for an asset in the database before committing it. You must first call SaveChanges, and then do a search.

+1
source share

All Articles