It is very strange to me. I have two entities. SalesStatus(Parent) and Sale(Child).
public class SalesStatus
{
[Key]
public int SalesStatusID { get; set; } /* this is identity column*/
public string Status { get; set; }
public virtual List<Sale> Sales { get; set; }
}
public class Sale
{
[Key]
public int SalesID { get; set; } /* this is identity column*/
//etc
}
SalesContext db = new SalesContext();
var ss = new SalesStatus
{
Status = "INQ",
Sales = new List<Sale>()
};
ss.Sales.Add(sale);
db.SalesStatus.Add(ss);
db.Entry(ss).State = EntityState.Added;
db.SaveChanges();
I've got a error. The Entity Framework tried to insert new record with PK value. "Cannot insert explicit value for identity column in table"
But when I changed the EntityState as EntityState.Detached or EntityState.Unchanged. the child entity(sale) was successfully inserted alone.(without SalesStatus)
I've been very confused.
I've found some case below. But it doesn't work to my case. EF Code First Parent-Child insertions with identity columns
I use dotnet framework 4.0 / entity framework 4.1