Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;}
}
like image 905
Jey Avatar asked Mar 26 '26 06:03

Jey


1 Answers

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);
like image 71
Eranga Avatar answered Mar 28 '26 19:03

Eranga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!