Entity Framework inserting row for navigation property even if key is found
-
28-06-2021 - |
문제
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;}
}
해결책
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);
다른 팁
You need to set the State
of your PersonCategory
to Unchanged
before you save your Person
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();