New Posts New Posts RSS Feed: An entity with this key already exists
  FAQ FAQ  Forum Search   Calendar   Register Register  Login Login

An entity with this key already exists

 Post Reply Post Reply
Author
iDave View Drop Down
Newbie
Newbie
Avatar

Joined: 27-Jun-2011
Location: Belgiƫ
Posts: 11
Post Options Post Options   Quote iDave Quote  Post ReplyReply Direct Link To This Post Topic: An entity with this key already exists
    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
Back to Top
kimj View Drop Down
IdeaBlade
IdeaBlade
Avatar

Joined: 09-May-2007
Posts: 1391
Post Options Post Options   Quote kimj Quote  Post ReplyReply Direct Link To This Post 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.
Back to Top
iDave View Drop Down
Newbie
Newbie
Avatar

Joined: 27-Jun-2011
Location: Belgiƫ
Posts: 11
Post Options Post Options   Quote iDave Quote  Post ReplyReply Direct Link To This Post 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!
Back to Top
 Post Reply Post Reply

Forum Jump Forum Permissions View Drop Down