Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework SaveChanges Return Error. AddObject Does not set Primary Key

I have a Property table and another is Detail table. Where I am using disconnected approach where multiple properties are added and then when we click the save button it will save changes to the database. This approach of not saving for every property added is because user can delete from the list also.

Here's what I am doing

foreach (Property P in Results)
{
  if(P.PropertyId==0 && P.EntityState==EntityState.Added)
    Repository.Properties.AddObject(P);
}

but when I try to save the data

public void Save()
{
  Repository.SaveChanges();
}

it returns error

Unable to determine the principal end of the 'database.FK_Details_Property'
relationship. Multiple added entities may have the same primary key.

I think its because every time I call AddObject its primary key is 0 and I don't know what could solve this problem. Is this similar or sounds familiar to anyone who has encountered it?

Thanks in advance

like image 615
user877127 Avatar asked Oct 18 '11 13:10

user877127


1 Answers

its definitely identity column related here.

Assuming your using MS SQL please check that on table your are inserting and any related ones that the

1) Identity Specification = YES

2) Is Identity = YES

3) Identity Increment = 1

4) Identity Seed = 1

Its definitely trying to insert the PK for you, so you need to look around there. Make sure you check child tables also. If you still have problems and your not using the code first method, try regenerate these tables in your EDMX also.

like image 90
Isuru Fonseka Avatar answered Nov 18 '22 23:11

Isuru Fonseka