'EF Insert to DB with related entities
I have an entity Employee that I need to insert into my SQL server DB. So I define my employee entity which has a phone number related object and phone number has a phone number type (like main, personal, etc..) The phone number type is a dictionary table so (PhoneNumberTypeId = 1) is already there. I'm populating the PhoneNumberType property with the related one because I need it later but when I try to SaveChanges is saying that I cannot insert PhoneNumberType with a specific id (since the column is identity), but my goal is not to insert the PhoneNumberType, I just add it for the navigation later. Is there any way that EF know that record already exists and ignore it? I tried also removing the "PhoneNumberTypeId = 1", and leave PhoneNumberType but the only way is working is keeping "PhoneNumberTypeId = 1" and removing PhoneNumberType but then later when I try to get the PhoneNumberType, is null because I didn't populate it. Maybe is a two step process.
new Employee
{
Name = "John Doo",
PhoneNumber = new PhoneNumber
{
PhoneNumberTypeId = 1,
PhoneNumberType = context.PhoneNumberTypes.FirstOrDefault(p => p.PhoneNumberTypeId.Equals(1)),
Number = "5143452234"
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
