Forum Discussion
IsabelFonseca
Feb 17, 2023Copper Contributor
Error -another entity of the same type already has the same primary key value
Good afternoon, I have an error, and I think you can help me. Error in Microsoft Visual Studio (Microsoft .NET Framework Version 4.8, EntityFramework 6.2): " System.InvalidOperationException ...
IsabelFonseca
Feb 27, 2023Copper Contributor
The situation was resolved.
public virtual void Update(T entity, int id) {
var aExists = dbSet.Find(id);
if (aExists == null) {
dbSet.Add(entity);
} else {
dataContext.Entry(aExists).State = EntityState.Detached; dbSet.Attach(entity);
dataContext.Entry(entity).State = EntityState.Modified;
}
}
Thanks.
public virtual void Update(T entity, int id) {
var aExists = dbSet.Find(id);
if (aExists == null) {
dbSet.Add(entity);
} else {
dataContext.Entry(aExists).State = EntityState.Detached; dbSet.Attach(entity);
dataContext.Entry(entity).State = EntityState.Modified;
}
}
Thanks.
- FurkanAyyildizSep 06, 2023Copper ContributorThanks, works very well
- AmirHosseinHasanlooAug 25, 2023Copper ContributorThank you very much, it helped me a lot