Prevent Adding New Record on Related Table Entity in Entity Framework

c# entity-framework entity-framework-6 orm

Question

On my entity, I'm attempting to add a new record. The issue is that linked entities are also adding new entries, even if everything functions well. Is it possible to prevent linked or second-level entities from adding new entries as well?

My example Entity Class is shown below:

public Tracking()
    {
        public string Details { get; set; }

        //Other properties here..

        [Required]
        public virtual Employee { get; set; }
    }

In essence, all I'm doing is obtaining the current Employee record, declaring it as my property, and adding 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 as intended; the issue is that my table Employee now has a second new Employee Record. That's not what I desire, however. I just want to update the employee record with a new Tracking record.

Is there a method to do this or am I lacking any code or setup with my Entity Framework?

1
4
2/15/2018 9:53:02 PM

Accepted Answer

ZZZ_tmp
3
2/15/2018 10:15:21 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow