0
votes

I have the Expedition Entity in my project.

     [Table("Expeditions")]
     public class Expedition
{

       public int Id { get; set; }
       public Bus Bus { get; set; }
       [ForeignKey("Bus")]
       public int BusId { get; set; }
}

And Expedition entity have a foreign key. Foreign key from the Bus Entity.

I create an EpeditionDTO with the information from the front-end.Want try to convert ExpeditionDTO to Expedition and add them to the database.

public void Add(ExpeditionDTO item)
        {
            try
            {
                Bus Bus = _mapper.Map<Bus>(item.Bus);
                var expedition = new Expedition()
                {
                    Id = item.Id,
                    Bus = Bus,
                    BusId = Bus.Id
                };
                _expeditionRepository.Add(expedition);
                _unitOfWork.Save();
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }

And my Add method like that:

public virtual void Add(T Entity)
        {
            _context.Add<T>(Entity);
        }

When I try this i get this error.

The instance of entity type ‘Bus’ cannot be tracked because another instance with the same key value for {‘Id’} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using ‘DbContextOptionsBuilder.EnableSensitiveDataLogging’ to see the conflicting key values.

How can i solve this problem.

1
You are creating a new Bus to assign to your Expedition. What you should be doing is retrieving the existing bus from the data store, OR actually just assigning the BusId would be enough. - Captain Kenpachi

1 Answers

0
votes

ou should pass only the BusId

var expedition = new Expedition()
                {
                    Id = item.Id,
                    BusId = Bus.Id
                };