Print Page | Close Window

An entity with this key already exists

Printed From: IdeaBlade
Category: DevForce
Forum Name: DevForce 2012
Forum Discription: For .NET 4.5
URL: http://www.ideablade.com/forum/forum_posts.asp?TID=4623
Printed Date: 21-Aug-2025 at 5:27pm


Topic: An entity with this key already exists
Posted By: iDave
Subject: An entity with this key already exists
Date Posted: 06-Dec-2013 at 7:17pm
Good day,

I've the following code:


Role role;
foreach (var department in departments)
{
    role = new Role();
    role.Name = department;

    em.AddEntity(role);
}

em.SaveChanges();


Which used to work fine. But when I cleaned up the db and executed this same code, I'm now getting the following error when adding the 2nd entity to AddEntity():

"An entity with this key: Role: 0 already exists in this EntityManager"

The Id is Primary Key and Identity auto-incremented by 1. But somehow the Id is not longer auto-incremented when being added to the EntityManager.

This is the data property of the RoleId, generated by DevForce:


    [Key]
    [DataMember]
    [Bindable(true, BindingDirection.TwoWay)]
    [Editable(true)]
    [Display(Name="Id", AutoGenerateField=true)]
    [IbVal.RequiredValueVerifier( ErrorMessageResourceName="Role_Id")]


And the script for the Role table:


CREATE TABLE [dbo].[Role](
    [Id] [smallint] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](25) NOT NULL,
 CONSTRAINT [PK_Role] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]


Could someone be so kind to point me out what is the problem?

Thanks in advance,
Dave



Replies:
Posted By: kimj
Date Posted: 08-Dec-2013 at 1:29pm
Check the DataEntityProperty DevForce generated for this.  The fifth parameter, for "isAutoIncrementing", should be true.  If not, either the generated code is out of sync with the database, or somehow incorrect.  If you regenerate the code it should sync up with your database.


Posted By: iDave
Date Posted: 09-Dec-2013 at 3:35pm
Hi,

Thanks for the prompt reply.
The fifth parameter of the DataEntityProperty was indeed set to false.
Regenerating the code or updating the model didn't solve the problem until I deleted the model and created it again.

Thanks a lot for the help, I do really appreciate it!

Have a nice day!



Print Page | Close Window