Sto cercando di aggiornare un record utilizzando Entity Framework 6, code-first, mappatura fluente o uno strumento come Automapper.L'aggiornamento dei dati esistenti in EF 6 genera un'eccezione: "... entità dello stesso tipo ha già lo stesso valore di chiave primaria."
L'entità (Employee
) presenta altre strutture composite ad esso associati come Addreess
(raccolta), Department
È anche ereditato da una base chiamata User
il metodo Save è il seguente, con _dbContext
essendo l'implementazione DbConext
public bool UpdateEmployee(Employee employee)
{
var entity = _dbContext.Employees.Where(c => c.Id == employee.Id).AsQueryable().FirstOrDefault();
if (entity == null)
{
_dbContext.Employees.Add(employee);
}
else
{
_dbContext.Entry(employee).State = EntityState.Modified; // <- Exception raised here
_dbContext.Employees.Attach(employee);
}
return _dbContext.SaveChanges() > 0;
}
continuo a ricevere l'errore:
Attaching an entity of type 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.
Ho provato quanto segue:
- Collegamento prima di impostare a
EntityState.Modified
- Aggiunta
AsNoTracking()
sulla query se l'oggetto esiste (Non fa eccezione, ma DB non è aggiornato) - https://stackoverflow.com/a/23228001/919426 - risparmio utilizzando l'entità di base
_dbContext.Users
invece dell'entità Dipendente - https://stackoverflow.com/a/25575634/919426
Nessuno dei quali funziona per me ora.
Cosa potrei aver sbagliato per alcune di quelle soluzioni non funzionare nella mia situazione?
use 'var entity = _dbContext.Employees.FirstOrDefault (c => c.Id == employee.Id);' – dotctor
Qual è la durata di 'dbContext'? Scommetto che non crei un nuovo contesto abbastanza spesso. –
Si prega di dare un'occhiata alla mia risposta su [ASP.NET MVC - Il collegamento di un'entità di tipo "MODELNAME" non è riuscito perché un'altra entità dello stesso tipo ha già lo stesso valore di chiave primaria] (http://stackoverflow.com/questions/ 23201907/asp-net-MVC-allegando-an-soggetto-di-tipo-ModelName-failed-perché-altro-ent/39557606 # 39557606). –