Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify if object is already inside Entity Framework context

I'm getting an issue while using EF4, when I'm trying to verify if object is already inside 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 my search after insertion, came out empty?

I know that the data is persisted after 'SaveChanges', but what if I need to 'query' my entity memory data.

Extending the question

I have a business rule that by adding 1 item A, triggers the insertion of others entities B. The issue is, I have validation rule that on insertion of B,t A must already exists.

Because all of these actions are made before 'SaveChanges', I get an error that EntityA doesn't exists.

Other case, I have a Name field that is unique on a table. If I try to run AddEntityName("bla") twice and then 'SaveChanges', I get an exception from DB [Unique constraints], even after passing my validation for insertion, that guaranties that a name is unique.

Anyone have any idea?

like image 265
muek Avatar asked Dec 09 '10 22:12

muek


2 Answers

When you do .AddObject, it adds it to EF's internal "graph" (memory) in a pending state of "Added".

Only once you do ctx.SaveChanges() will the changes be persisted to the underlying store.

The query you are writing is against the database, and the change hasn't been persisted yet.

So if you execute your query after you do ctx.SaveChanges(), the count will be as expected.

On a side note, if you want to see if an entity is already in the graph (e.g before you "Attach"), read up on ObjectStateManager.TryGetObjectStateEntry.

like image 103
RPM1984 Avatar answered Sep 19 '22 04:09

RPM1984


I haven't used EF4 but have used the previous version so I don't know if their is a different expectation in EF4. It looks like you are attempting to search for the asset in the DB before actually committing it. You should call SaveChanges first then search for it.

like image 29
Michael Gattuso Avatar answered Sep 19 '22 04:09

Michael Gattuso