locked
The instance of entity type 'Component' cannot be tracked because another instance with the same key value for {'ComponentId'} is already being tracked RRS feed

  • Question

  • User970350993 posted

    Hi I m doing CRUD operation in Blazor using EF. It is fine for first instance . I am getting the below exception only while doing insert then delete or update operation

    'The instance of entity type 'Component' cannot be tracked because another instance with the same key value for 
    {'ComponentId'} 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.'

    My UI Code

    <EditForm Model="objComp"  OnValidSubmit="CreateComponent">
        <div class="row">
            <div class="col-md-8">
                <div class="form-group">
                    <label for="Name" class="control-label">Name</label>
                    <SfTextBox ID="txtComponent" @bind-Value="@objComp.ComponentName"></SfTextBox>
                    <ValidationMessage For="@(()=> objComp.ComponentName)" />
                </div>
    
                <div class="form-group">
                    <label for="ServiceCategory" class="control-label">Service Category</label>
    
                    <SfDropDownList TValue="int?"  Placeholder="Select"  TItem="ServiceCategory" @bind-Value="@objComp.ServiceCategogyId" DataSource="@LocalData">
                        <DropDownListFieldSettings Text="ServiceCategoryName" Value="ServiceCategoryId"></DropDownListFieldSettings>
                    </SfDropDownList>
                    <ValidationMessage For="@(()=> objComp.ServiceCategogyId)" />
                </div>
    
            </div>
        </div>
        <div class="row">
            <div class="col-md-4">
                <div class="form-group">
                    <button type="submit" class="btn btn-primary">@ButtonName</button>
                    <a href="/componets" class="btn btn-primary">Cancel</a>
                </div>
            </div>
        </div>
    </EditForm>
    
    <p>Grid Details</p>
    <div>
        <div id="target" style="height: 500px;">
            <SfGrid ID="Grid" @ref="gridObj"
                    DataSource="@componentVM"
                    AllowPaging="true"
                    AllowSorting="true"
                    AllowResizing="true"
                    AllowReordering="true">
                <GridPageSettings PageSize="5"></GridPageSettings>
                <GridEvents CommandClicked="OnCommandClicked"
                            TValue="ComponentViewModel">
                </GridEvents>
                <GridColumns>
                    <GridColumn IsPrimaryKey="true" Field=@nameof(objCVM.ComponentId)
                                HeaderText="ID #" TextAlign="@TextAlign.Left" Width="40">
                    </GridColumn>
                    <GridColumn Field=@nameof(objCVM.ComponentName)
                                HeaderText="ComponentName" TextAlign="@TextAlign.Left" Width="150">
                    </GridColumn>
                    <GridColumn Field=@nameof(objCVM.ServiceCategoryName)
                                HeaderText="ServiceCategoryName" TextAlign="@TextAlign.Left" Width="150">
                    </GridColumn>
                    <GridColumn HeaderText="Action" TextAlign="TextAlign.Left" Width="90">
                        <GridCommandColumns>
                            <GridCommandColumn Type=CommandButtonType.Edit
                                               ButtonOption="@(new CommandButtonOptions()
                                                                   { Content = "Edit" })">
                            </GridCommandColumn>
                            <GridCommandColumn Type=CommandButtonType.Delete
                                               ButtonOption="@(new CommandButtonOptions()
                                                                   { Content = "Delete" })">
                            </GridCommandColumn>
                        </GridCommandColumns>
                    </GridColumn>
                </GridColumns>
            </SfGrid>
        </div>
    </div>

    C# Code

    @code {
        SfGrid<ComponentViewModel> gridObj;
        public string ButtonName { get; set; }
        public List<ComponentViewModel> componentVM { get; set; }
        private Component objComp = new Component();
        public ComponentViewModel objCVM = new ComponentViewModel();
        ServiceCategory objServ = new ServiceCategory();
        protected override void OnInitialized()
        {
            ButtonName = "Save";
            componentVM = ComponentService.GetComponents();
        }
        protected void DataRefresh()
        {
            componentVM = ComponentService.GetComponents();
            objComp.ComponentName = string.Empty;
            objComp.ComponentId = 0;
            StateHasChanged();
    
        }
        protected void CreateComponent()
        {
            try
            {
                if (ButtonName.Equals("Save"))
                {
    
                    objComp.ComponentId = objCVM.ComponentId;
                    objComp.ComponentName= objCVM.ComponentName;
                    objComp.ServiceCategogyId = objCVM.ServiceCategogyId;
                    ComponentService.Create(objComp);
                    StateHasChanged();
                    DataRefresh();
                }
                else
                {
                    objComp.ComponentId = objCVM.ComponentId;
                    objComp.ComponentName = objCVM.ComponentName;
                    objComp.ServiceCategogyId = objCVM.ServiceCategogyId;
                    ComponentService.UpdateComp(objComp);
                    StateHasChanged();
                    DataRefresh();
                    ButtonName = "Save";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public void OnCommandClicked(CommandClickEventArgs<ComponentViewModel> args)
        {
            objComp = ComponentService.GetComponentById(args.RowData.ComponentId);
            if (args.CommandColumn.ButtonOption.Content == "Edit")
            {
                ButtonName = "Update";
                objComp.ComponentName = args.RowData.ComponentName;
                objComp.ServiceCategogyId = objComp.ServiceCategogyId;
            }
            if (args.CommandColumn.ButtonOption.Content == "Delete")
            {
                string msg = ComponentService.DeleteComp(objComp);
                DataRefresh();
            }
        }
        void Cancel()
        {
            objNavigationManager.NavigateTo("componets");
        }

    DAL Layer Code

    namespace CarInspectionApp.Data
    {
        public class ComponentService : IComponentService
        {
            private readonly CarinspectionContext _db;
            public ComponentService(CarinspectionContext db)
            {
                _db = db;
            }
            public string Create(Component component)
            {
                _db.Component.Add(component);
                _db.SaveChanges();
                _db.Entry(component).State = EntityState.Detached;
                return "Save Successfully";
            }
    
            public string DeleteComp(Component comp)
            {
                _db.Remove(comp);
                _db.SaveChanges();
                _db.Entry(comp).State = EntityState.Detached;
                return "Data has been deleted";
            }
    
            public Component GetComponentById(int Id)
            {
                Component comp = _db.Component.AsNoTracking()
                                 .FirstOrDefault(s => s.ComponentId == Id);
                return comp;
            }
    
            public List<ComponentViewModel> GetComponents()
            {
                var compList = (from cc in _db.Component.AsNoTracking()
                                join sc in _db.ServiceCategory.AsNoTracking()
                                on cc.ServiceCategogyId equals sc.ServiceCategoryId into ps
                                from kk in ps.DefaultIfEmpty()
                                orderby cc.ComponentId descending
                                select new ComponentViewModel
                                {
                                    ComponentId = cc.ComponentId,
                                    ComponentName = cc.ComponentName,
                                    ServiceCategoryName = kk.ServiceCategoryName
                                }).ToList();
    
                //var compList = _db.Component
                //               .Include(c => c.ServiceCategogy)
                //               .ToList();
    
                return compList;
            }
    
            public string UpdateComp(Component component)
            {
                _db.Component.Update(component);
                _db.SaveChanges();
                return "Data has been updated";
            }
            public void Dispose()
            {
                _db.Dispose();
            }
        }

    could you suggest me, where is the problem ?

    Monday, November 9, 2020 10:59 AM

Answers

  • User970350993 posted

    I got the solution, there was problem with Component binding, I was not using viewmodel instance. and there was other typo error on delete method on EF code.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, November 9, 2020 2:33 PM