Here is the simple case.
I have a Customer record defined like this:
public class Customer
{
[Key]
public string Id { get;}
public UsState UsState { get; set; }
}
public class UsState
{
[Key]
public string StateAbbreviation {get;set;}
public string StateName {get;set;}
}
I already have my UsState’s populated with the 50 states, now I want to insert one Customer record that ties to an existing state.
If I say something like:
Customer customer = new Customer()
{
UsState = "CA",
Id = 1001
}
dbContext.Customers.add(customer);
I get an error saying state is trying to be inserted again.
How can I get the add to use an existing state and not try and re-insert it. My real problem has lots of nested objects that may exist so I need to solve this in general.
Thanks
Two ways I know is:
Set EntityState to what is appropriate for your action or
Get the UsState from the database and add it to the customer right before saving, which will give it an EntityState of UnModified or something like that.
to change the EntityState you need to get to the ObjectContext of your DbContext like shown in this thread: Entity Framework Code First – No Detach() method on DbContext