Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failed because another entity of the same type already has the same primary key value As

How to fix error..

When update record show this error:

Show error : {"Attaching an entity of type 'DomainClass.WorkshopReport' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate."}

Domain Class:

namespace DomainClass
{
    public class WorkshopReport
    {
        public int Id { set; get; }
        public int UserId { set; get; }
        public int? ManagerIdConfirm { set; get; }
        public bool? ManagerConfirmState { set; get; }
        public DateTime? ManagerConfirmDateTime { set; get; }
        public int? SuperviderIdConfirm { set; get; }
        public bool? SuperviderConfirmState { set; get; }
        public DateTime? SuperviderConfirmDateTime { set; get; }
        public string ReportNumber { set; get; }
        public string Shift { set; get; }
        public string ShiftWork { set; get; }
        public DateTime ShiftDate { set; get; }
        public string ShiftPersennel { set; get; }
        public string Type { set; get; }
        public DateTime SubmitDateTime { set; get; }
    }
}

Interface Repository:

namespace InterfaceRepository
{
    public interface IWorkshopReportRepository
    {
        IQueryable<WorkshopReport> Get();
        bool Save();
        bool Add(WorkshopReport newValue);
        bool Delete(WorkshopReport deleted);
        bool Edit(WorkshopReport updated);
        IQueryable<WorkshopReport> FindById(int Id);
        IQueryable<WorkshopReport> Search(string ReportNumber);
    }
}

Repository Layer:

 namespace RepositoryLayer
{
    public class WorkshopReportRepository:IWorkshopReportRepository
    {
        public CMSDataContext _ctx;
        public WorkshopReportRepository(CMSDataContext ctx)
        {
            _ctx = ctx;
        }
        public IQueryable<WorkshopReport> Get()
        {
            return _ctx.WorkshopReports;
        }

        public bool Save()
        {
            try
            {
                return _ctx.SaveChanges() > 0;
            }
            catch (Exception ex)
            {
                // TODO log this error
                return false;
            }
        }
        public bool Add(WorkshopReport newValue)
        {
            try
            {
                _ctx.WorkshopReports.Add(newValue);
                return true;
            }
            catch (Exception ex)
            {
                // TODO log this error
                return false;
            }
        }

        public bool Delete(WorkshopReport deleted)
        {

            try
            {
                _ctx.WorkshopReports.Remove(deleted);
                return true;
            }
            catch (Exception ex)
            {
                // TODO log this error
                return false;
            }
        }


        public bool Edit(WorkshopReport updated)
        {
            try
            {
                _ctx.Entry(updated).State = System.Data.Entity.EntityState.Modified;
                return true;
            }
            catch (Exception ex)
            {
                // TODO log this error
                return false;
            }
        }

        public IQueryable<WorkshopReport> Search(string Value)
        {
            return _ctx.WorkshopReports.Where(i => i.ReportNumber.Contains(Value));
        }

        public IQueryable<WorkshopReport> FindById(int Id)
        {
            return _ctx.WorkshopReports.Where(i => i.Id == Id);
        }
    }
}

Workshop Controller:

public ActionResult Edit(WorkshopReport value, FormCollection formvalue)
        {
            try
            {

                    value.ShiftDate =
                        _calenderRepository.ConvertPersianToEnglishFormat(formvalue["ShiftDate"].ToString());
                    value.SubmitDateTime=DateTime.Now;
                    value.Type = internalType;
                    value.UserId= _userRepository.FindByEmail(User.Identity.Name).Id;
                    if (_workshopReportRepository.Edit(value))
                    {
                        _workshopReportRepository.Save();
                        TempData["Success"] = "Updated";
                    }

            }
            catch (Exception)
            {
                TempData["Error"] = "Try again...";
            }
            return RedirectToAction("Index", "WorkshopReport", new { type = internalType });

Show error on Repository Layer: image of this error

like image 958
Mehrdad Ghaffari Avatar asked Mar 07 '23 05:03

Mehrdad Ghaffari


1 Answers

The problem was solved this way.

public bool Edit(WorkshopReport updated)
        {
            try
            {
                var local = _ctx.Set<WorkshopReport>()
                    .Local
                    .FirstOrDefault(f => f.Id == updated.Id);
                if (local != null)
                {
                    _ctx.Entry(local).State = EntityState.Detached;
                }
                _ctx.Entry(updated).State = System.Data.Entity.EntityState.Modified;
                return true;
            }
            catch (Exception ex)
            {
                // TODO log this error
                return false;
            }
        }
like image 137
Mehrdad Ghaffari Avatar answered Apr 08 '23 13:04

Mehrdad Ghaffari