I got this error when I go to submit the object from a list in MVC 5, and it is always happening in the second item of list
I use this to call the database method;
foreach (var modulo in _Modulos)
{
USERS_MODULO _modulo = new USERS_MODULO();
_modulo = modulo;
_modulo.USUARIO = usuario;
_PermissoesLinxDB.SalvaModulosUser(_modulo);
_modulo = null;
}
Line 86: { Line 87: DBRetaguardDataContext dbRetaguard = new DBRetaguardDataContext(); Line 88:
dbRetaguard.USERS_MODULOs.InsertOnSubmit(modulo); Line 89:
try Line 90: {Source File: c:\SOURCESAFE\Projetos\EMS\EMS.Dados\Controles\PermissoesLinxDB.cs
Line: 88Stack Trace:
[NotSupportedException: An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported.]
System.Data.Linq.StandardChangeTracker.Track(MetaType mt, Object obj, Dictionary2 visited, Boolean recurse, Int32 level) +891018
1.InsertOnSubmit(TEntity entity) +172
System.Data.Linq.StandardChangeTracker.Track(Object obj, Boolean recurse) +83 System.Data.Linq.StandardChangeTracker.Track(Object obj) +12 System.Data.Linq.Table
The problem is that _modulo
and modulo
are the SAME object. Both variables reference the same object.
What you are doing right now with _modulo = modulo;
is NOT copying modulo
to the new object but instead setting the reference for _modulo
to the exact same point in memory of modulo
. References are equal.
Then, when you call _PermissoesLinxDB.SalvaModulosUser(_modulo);
it is actually trying to save(?) the already existing object, modulo
and throwing an exception because it already exists.
What I think you intend to do is something like the following which is to 1) create a new object, 2) assign the internal values of another object to it, and finally 3) save the new object:
USERS_MODULO _modulo = new USERS_MODULO();
// assign each property from the old object to this brand new object
_modulo.PropertyA = modulo.PropertyA; // obviously, substitute your property names
_modulo.PropertyB = modulo.PropertyB;
_modulo.PropertyC = modulo.PropertyC;
// etc..