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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With