I am trying to add new record on my entity. It works fine, the problem is, the related entities are adding new records as well. Is there a way to stop related or 2nd level entities to be inserting new records as well?
Here is my sample Entity Class:
public Tracking()
{
public string Details { get; set; }
//Other properties here..
[Required]
public virtual Employee { get; set; }
}
Basically I am just getting the existing Employee record then declare it on my property, then add the the Tracking record:
Employee emp = _dbContext.EmployeeRepo.GetEmployeeByID(1001);
Tracking track = new Tracking()
{
Details = "My details here",
Employee = emp
}
_dbContext.TrackingRepo.Add(track);
_dbContext.SaveChanges();
This code works fine, the problem is that, another new Employee Record is inserted on my table Employee. Which is not what I want. I just want to add a new record of Tracking with the existing employee record.
So is there a way to do this or I am missing a configuration or code with my Entity Framework?
You need to set/mark the employee as
Unchanged
orAttach
the entityIf you have an entity that you know already exists in the database but which is not currently being tracked by the context then you can tell the context to track the entity using the Attach method on
DbSet
. The entity will be in the Unchanged state in the contextNote that no changes will be made to the database if
SaveChanges
is called without doing any other manipulation of the attached entity. This is because the entity is in the Unchanged state.Another way to attach an existing entity to the context is to change its state to Unchanged.
EntityState Enumeration
Entity Framework Add and Attach and Entity States
Entity states and SaveChanges
An entity can be in one of five states as defined by the EntityState enumeration. These states are:
SaveChanges does different things for entities in different states: