Jey
Jey

Reputation: 37

Entity Framework inserting row for navigation property even if key is found

I am using Entity Framework. I have a table Person that has a foreign key on Table PersonCategory. Person Id is an auto-incremented identity (1,1). Each time i update the person entity the entity framework inserts a row for PersonCategory Table Even if category is found.

I am using Database first design.

class Person
{
  public string Name {get;set}
  public PersonCategory {get;set;}
}

class PersonCategory
{
  public int ID {get;set}
  public string Name{get;set;}
}

Upvotes: 3

Views: 6241

Answers (3)

Eranga
Eranga

Reputation: 32447

First you need to attach the existing PersonCategory to the context;

var myPersonCat = new PersonCategory { ID = 1, Name = "Foo" };
var myPerson = new Person { Name = "Bar", PersonCategory = myPersonCat };

context.PersonCategories.Attach(myPersonCat);    
context.People.Add(myPerson);

Upvotes: 7

Giorgio Minardi
Giorgio Minardi

Reputation: 2775

Can you post the code you're using to update? Sounds to me that you're adding a new person everytime, and with a person category get added for the new record. What you want is retrieve the person you want from the EF context, update the fields you want, and persist the changes to the context, without adding any new element to your db, this way you're only modifying an existing record, existing relationships will be maintained. Something like

var myPerson = context.People.FindbyId(personId);
myPerson.Name = "Joe";
myPerson.Age = "20";

context.SaveAllChanges();

Upvotes: 0

podiluska
podiluska

Reputation: 51504

You need to set the State of your PersonCategory to Unchanged before you save your Person

Upvotes: 0

Related Questions