Entity is not attached exception

Discussion of open issues, suggestions and bugs regarding LinqConnect – Devart's LINQ to SQL compatible ORM
Post Reply
-marcelo-
Posts: 26
Joined: Wed 28 Jun 2017 12:35

Entity is not attached exception

Post by -marcelo- » Tue 17 Jul 2018 19:42

I´m using version 4.4.727 for Postgresql.
My app allows users to query the database, and navigate the resulting list.
When the user attempts to update or delete one of the records, the code tries to get a "fresh" version from the database; if some of the properties are changed (by another user) the operation is cancelled, the new value/s are displayed and the user is alerted.
To get the "current" version from the DB, I use

Code: Select all

Entity currentInDb = context.Entities.GetOriginalEntityState(currentDisplayed);

This code works fine a few times; but most often it throws "Entity is not attached".
Also, I modified the code, so if there are changes among instances, the new (read from db) instance is Attached.
Nevertheless, the error persists.
a) What am I doing the wrong way?
b) Is there another path to get the same results?

My first approach was

Code: Select all

Entity currentindb = (from e in context.Entities 
	where e.Id == currentDisplayed.Id
	select e).FirstOrDefault();

but this code don´t read the entity from the database, it gets the value from the Attached instances, so is not aware of changes.
TIA

Shalex
Site Admin
Posts: 9543
Joined: Thu 14 Aug 2008 12:44

Re: Entity is not attached exception

Post by Shalex » Fri 20 Jul 2018 19:39

-marcelo- wrote: Tue 17 Jul 2018 19:42To get the "current" version from the DB, I use

Code: Select all

Entity currentInDb = context.Entities.GetOriginalEntityState(currentDisplayed);
1. You can get the "current" version from the DB with context.Refresh(RefreshMode,Object).
-marcelo- wrote: Tue 17 Jul 2018 19:42This code works fine a few times; but most often it throws "Entity is not attached".
Also, I modified the code, so if there are changes among instances, the new (read from db) instance is Attached.
Nevertheless, the error persists.
a) What am I doing the wrong way?
2. Try using strong references (instead of default weak references): https://www.devart.com/linqconnect/docs ... ntity.html. If this doesn't help, please localize the issue in a small test project and upload it with the corresponding DDL/DML script to ftp://ftp.devart.com (credentials: anonymous / yourEmail).
-marcelo- wrote: Tue 17 Jul 2018 19:42b) Is there another path to get the same results?

My first approach was

Code: Select all

Entity currentindb = (from e in context.Entities 
	where e.Id == currentDisplayed.Id
	select e).FirstOrDefault();

but this code don´t read the entity from the database, it gets the value from the Attached instances, so is not aware of changes.
3. You can use your "first approach" query with the newly created context instance to get data from database.

Post Reply