Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 6 - .Create new object, save changes, re-query object based on new id, null return

I recently upgraded our solution from EF4.1 to EF6. Our previous create method added the detached object to the context, saved changes, then requeried the object based on the new id. We requery the object because we do not use lazy loading, and use includes/selects to get navigational properties - which are added by taking the IDbSet and returning an IQueryable. In short, I cannot just return the existing in-memory copy - because it would not be fully loaded up. I have tried detaching the in-memory copy. I cannot flush the dbcontext (because I am working with other objects in the same context).

Anyway, the big issue, my big issue is that in the EF6 branch when I requery that object it returns a null record - not finding the one I just created. The record is persisted to the database - I can see it. If I create a new dbcontext and query for that record I can find it.

dbContext.Set<TEntity>().Add(model);

dbContext.SaveChanges();

var newCopy = dbContext.Set<TEntity>().SingleOrDefault(p => p.Id == model.Id);

In this instance, newCopy is always null. But if I get a new dbContext - I can get the object fine.

Anyway, I need to solve this issue. Any ideas?

like image 280
Dan Hirsch Avatar asked Apr 21 '26 16:04

Dan Hirsch


1 Answers

I actually discovered what the issue was/is. In EF4, it really doesn't matter if the mappings are HasRequired or HasOptional. However, if you use a HasRequired on a nullable integer field (legacy db) - then it actually is performing an inner join and will not select the record - resulting in a return of null. Since I am not using lazy loading - but rather eager loading - if I have an include on the above described mapped field - it returns a null.

Thanks everyone for their help - it was appreciated!

like image 146
Dan Hirsch Avatar answered Apr 23 '26 06:04

Dan Hirsch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!