Note that there are some explanatory texts on larger screens.

plurals
  1. POasp.net mvc System.Data.Linq.DuplicateKeyException on update
    primarykey
    data
    text
    <p>I'm using asp.net mvc with linq to sql repositories and the following code is throwing an mvc System.Data.Linq.DuplicateKeyException exception on this._table.Attach(entity)</p> <p>My code is something like that:</p> <pre><code> public ActionResult Edit(int id) { return View(_controllerRepository.GetById(id)); } public ActionResult Edit(Directivo entity) { try { _repository.Save(entity, this.UserName) } catch (Exception ex) { return View(ex); } } </code></pre> <p>And in the repository:</p> <pre><code> public virtual void Save(T entity, string userName) { if (0 == entity.Id) { entity.UsuarioIntroduccion = userName; entity.FechaIntroduccion = DateTime.Now; entity.UsuarioModificacion = null; entity.FechaModificacion = null; this._table.InsertOnSubmit(entity); } else { entity.UsuarioModificacion = userName; entity.FechaModificacion = DateTime.Now; this._table.Attach(entity); this._table.Context.Refresh(RefreshMode.KeepCurrentValues, entity); } try { this._dataContext.SubmitChanges(); } catch (SqlException ex) { throw new DataContextException(ex); } } </code></pre> <p>Note that the Id isn't 0.</p> <p>Its really weird because it happens only with this class, i have a couple more that are working well.</p> <p>The table is that:</p> <pre><code>CREATE TABLE [Directivo]( [Id] [int] IDENTITY(1,1) NOT NULL, [Nombre] [varchar](45) NOT NULL, [Apellidos] [varchar](60) NOT NULL, [FechaNacimiento] [datetime] NULL, [CargoDirectivoId] [int] NOT NULL, [PathImagen] [varchar](250) NULL, FechaIntroduccion datetime not null, UsuarioIntroduccion varchar(45) not null, FechaModificacion datetime, UsuarioModificacion varchar(45), PRIMARY KEY (Id), FOREIGN KEY (CargoDirectivoId) REFERENCES CargoDirectivo(Id) ON DELETE NO ACTION ON UPDATE NO ACTION ) </code></pre> <p>And the class is the autogenerated by linq and a partial class that makes it inherit an interface, and sets the buddy class for metadata to use xVal</p> <p>Do you have any clues about what could be happening?</p> <p>Thanks in advance!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload