Entity is already beeing tracked C#

IliusNand1 1 Reputation point
2022-05-01T07:40:06.63+00:00

I want to program a application using C# completely. I get the error message The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked. What can I do? Please read my code provided.

        // GET: api/People
        [HttpGet]
        public async Task<ActionResult<IEnumerable<PeopleDTO>>> GetPeople()
        {
            return await _context.People.Select(p => new PeopleDTO(p)).ToListAsync();
        }

        // GET: api/People/5
        [HttpGet("{id}")]
        public async Task<ActionResult<PeopleDTO>> GetPeople(int id)
        {

            var People = await _context.People.FindAsync(id);

            if (People == null)
            {
                return NotFound();
            }

            return new PeopleDTO(People);
        }

        // GET: api/Peoples/5/Connector
        [HttpGet("{id}/Connector")]
        public async Task<ICollection<ZimmerDTO>> GetPeopleZimmer(int id)
        {
            var People = await _context.People.FindAsync(id);

            var connectorAll = await _context.Connectors.Select(a => new ConnectorDTO(a)).ToListAsync();
            var connectorPeople = await _context.ConnectorPeoples.Select(a => new ConnectorPeopleDTO(a)).ToListAsync();

            ICollection<ConnectorDTO> connectorList = new Collection<ConnectorDTO>();

            if (People == null)
            {
                return connectorList;
            }

            foreach (ConnectorPeopleDTO connectorPeopleItem in connectorPeople)
            {
                if (connectorPeopleItem.PeopleId == id)
                {
                    Connector c = await _context.Connectors.FindAsync(connectorPeopleItem.ConnectorId);
                    ConnectorDTO cD = new ConnectorDTO(c);
                    ConnectorList.Add(cD);
                }
            }

            return connectorList;
        }

        // GET: api/Peoples/5/Res
        [HttpGet("{id}/Reservierungen")]
        public async Task<ICollection<ResDTO>> GetPeopleRes(int id)
        {

            List<Res> res = await _context.Res.Include(x => x.ConnectorPeople).ToListAsync();

            IEnumerable<Res> rdtso = res.Where(x => x.ResPeople.PeopleId == id);

            ICollection<ResDTO> resList = new Collection<ResDTO>();

            foreach (Res resItem in rdtso)
            {
                Res temp = resItem;
                ResDTO rtemp = new ResDTO(temp);
                resList.Add(rtemp);
            }

            return resList;
        }

        // PUT: api/Peoples/5
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPut("{id}")]
        public async Task<IActionResult> PutPeople(int id, PeopleDTO h)
        {

            People People = new People();
            People = h.convertToEntity();

            if (id != People.PeopleId)
            {
                return BadRequest();
            }

            _context.Entry(People).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PeopleExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/Peoples
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPost]
        public async Task<ActionResult<PeopleDTO>> PostPeople(PeopleDTO h)
        {

            People People = new People();
            People = h.convertToEntity();

            _context.Peoples.Add(People);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetPeople", new { id = People.PeopleId }, People);
        }

        // DELETE: api/Peoples/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeletePeople(int id)
        {
            var People = await _context.Peoples.FindAsync(id);
            if (People == null)
            {
                return NotFound();
            }

            IList<ConnectorPeopleDTO> connectorPeopleList = await _context.ConnectorPeoples.AsNoTracking().Select(a => new ConnectorPeopleDTO(a)).ToListAsync();

            foreach (ConnectorPeopleDTO connectorItem in connectorPeopleList)
            {
                if (connectorItem.PeopleId == id)
                {
                    _context.ConnectorPeoples.Remove(connectorItem.convertToEntity());
                }
            }

            _context.Peoples.Remove(People);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        private bool PeopleExists(int id)
        {
            return _context.Peoples.Any(e => e.PeopleId == id);
        }
    }
}


        public void ConfigureServices(IServiceCollection services)
        {

            services.AddDbContext<PeopContext>(options => { });
        }

// personDetail

      <f:metadata>
         <f:viewParam name="personId" value="#{peopleBean.person.personId}"/>
         <f:viewAction action="#{peopleBean.loadData}"/>
      </f:metadata>

    public void loadData() throws ApiException {
        hotel = zimmerHotelApi.apiHotelsIdGet(hotel.getHotelId());
        zimmerHotel = zimmerHotelApi.apiHotelsIdZimmerGet(hotel.getHotelId());
    }


// LoginBean


@RequestScoped
@Named
public class LoginBean implements Serializable {

    private User user = new User();

    @PostConstruct
    public void init() {

    }

    public String login() {
        if (user.getUsername().equals("admin") && user.getPassword().equals("admin")) {
            HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
            request.getSession().setAttribute("user", user);
            return ("index.xhtml?faces-redirect=true");
        }
        return "";
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}


// Login

<h:body>
    <h:form>
        <h3>Hotel Login</h3>
        <span class="ui-float-label">
       <p:inputText id="float-input" value="#{loginBean.user.username}"/>
       <p:outputLabel for="@previous" value="Username"/>
   </span>

        <span class="ui-float-label">
        <p:password id="pass" value="#{loginBean.user.password}"/>
        <p:outputLabel for="@previous" value="Password"/>
   </span>

        <h:commandButton action="#{loginBean.login}"
                         value="Login"></h:commandButton>

    </h:form>
</h:body>
Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
725 questions
{count} votes

1 answer

Sort by: Most helpful
  1. IliusNand1 1 Reputation point
    2022-05-01T19:00:14.723+00:00

    Thank you.

    Where should the entity been converted? Not here?

            public Person convertToEntity()
            {
    
                Person p = new Person();
    
                p.PersonId= this.PersonId;
                p.Firstname= this.Firstname;
                p.Lastname= this.Lastname;
    
                return temp;
            }
    
    <DataGrid ItemsSource="{Binding .}" CanUserAddRows="False" AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTextColumn x:Name="personName" Binding="{Binding Name, UpdateSourceTrigger=PropertyChanged}" Header="Personname"/>
                    <DataGridTextColumn x:Name="personFirstname" Binding="{Binding Firstname, UpdateSourceTrigger=PropertyChanged}" Header="Personlast" SortDirection="Ascending"/>
                </DataGrid.Columns>
            </DataGrid>
    
    <ComboBox HorizontalAlignment="Left" Margin="639,66,0,0" VerticalAlignment="Top" Width="120" ItemsSource="{Binding .}" DisplayMemberPath="FirstName"/>
    
    
        private void personGrid_RowEditEnding(object gr, DataGridRowEditEndingEventArgs e)
        {
    
            PersonDTO p = (PersonDTO)e.Row.Item;
            if (p.PersonId == n)
            {
                client.PeopleAsync(p);
            }
            else
            {
               peopleClient.People3Async(p.PersonId, p);
            }
    
            personGrid.ItemsSource = client.PersonAllAsync().Result;
            personGrid.Items.Refresh();
        }