views:

207

answers:

0

Hello,

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)

My code is something like that:

    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);
        }
    }

And in the repository:

    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);
        }

    }

Note that the Id isn't 0.

Its really weird because it happens only with this class, i have a couple more that are working well.

The table is that:

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 
)

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

Do you have any clues about what could be happening?

Thanks in advance!