问题
I am retrieving a list of entities from a table FattureFornitori
, and loading also a collection owned by them (Voci, plural form - Voce, singular form) and a reference from each Voce
to a TipoCosto
entity:
var db = new DbGestPre();
db.Configuration.ProxyCreationEnabled = false;
var s = db.FattureFornitori
.Include(x => x.Voci)
.Include(x => x.Voci.Select(y => y.TipoCosto))
.AsNoTracking().ToList();
Now, multiple Voci
within a single FattureFornitori
can reference the same TipoCosto
.
So, when I try to attach a single FattureFornitori
with its Voci and the referenced TipoCosto
, I face the following error:
System.InvalidOperationException: 'Attaching an entity of type 'GP.Model.TipoCosto' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.'
Some debugging for that one FattureFornitori entity, here named ff, reveals:
ff.Voci[1].IdTipoCosto == ff.Voci[0].IdTipoCosto
true
ff.Voci[1].TipoCosto == ff.Voci[0].TipoCosto
false
So Entity Framework creates multiple instances for the same entity! So the error raised by the attach method makes sense. But how to solve this situation?? I looked after GraphDiff and other tools like those but they cannot help. Any hint? Thanks!!
回答1:
As Gert Arnold suggests, one workaround is to remove AsNoTracking(). But this means that the DB context will add ALL the entities to the tracked entities, so it will perform badly.
I tried the following code:
var db = new DbGestPre();
db.Configuration.ProxyCreationEnabled = false;
db.Configuration.AutoDetectChangesEnabled = false;
var s = db.FattureFornitori
.Include(x => x.Fornitore)
.Include(x => x.Voci)
.Include(x => x.Voci.Select(y => y.TipoCosto));
List<FatturaFornitore> data = s.ToList();
db.Dispose();
To quickly detach the entities from the context, I Disposed the context. Any faster/better approaches are welcome. This code ran in 858ms.
My former alternative
var db = new DbGestPre();
db.Configuration.ProxyCreationEnabled = false;
var s = db.FattureFornitori
.Include(x => x.Fornitore)
.Include(x => x.Voci)
.Include(x => x.Voci.Select(y => y.TipoCosto))
.AsNoTracking();
List<FatturaFornitore> data = s.ToList();
ran in just 500 ms.
So I am still looking for a way to make this version of the code with AsNoTracking working.
来源:https://stackoverflow.com/questions/61858801/entity-framework-6-attaching-a-graph-of-entities-queried-with-asnotracking