1

I'm trying to update a single value in the database using Entity Framework code-first.

It's throwing the following error:

Attaching an entity of type 'WarehouseAPI.Core.DataEntities.Models.TaskDetail' 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.

[Table("tblTaskDetail")]
public partial class tblTaskDetail
{
    [Key]
    public int TaskDetailID { get; set; }

    public int? ScheduleId { get; set; }

    [Required]
    [StringLength(50)]
    public string RobotID { get; set; }

    public Guid? SessionID { get; set; }

    [Required]
    [StringLength(50)]
    public string TaskStatus { get; set; }

    [Column(TypeName = "datetime2")]
    public DateTime? TaskScheduledOn { get; set; }

    [StringLength(250)]
    public string TaskSummary { get; set; }

    [Column(TypeName = "datetime2")]
    public DateTime? TaskStartedOnUtc { get; set; }

    [Column(TypeName = "datetime2")]
    public DateTime? TaskCompletedOnUtc { get; set; }
}

public class TaskDetail
{
    public int TaskDetailID { get; set; }
    public int? ScheduleId { get; set; }
    public string RobotID { get; set; }
    public Guid? SessionID { get; set; }
    public string TaskStatus { get; set; }
    public DateTime TaskScheduledOn { get; set; }
    public string TaskSummary { get; set; }
    public DateTime TaskStartedOnUtc { get; set; }
    public DateTime TaskCompletedOnUtc { get; set; }
}

public class TaskDetailMapper:EntityTypeConfiguration<TaskDetail>
{
    public TaskDetailMapper()
    {
        this.ToTable("tblTaskDetail");
        this.HasKey(hk => hk.TaskDetailID);
        this.Property(o => o.RobotID).HasColumnName("RobotID");
        this.Property(o => o.ScheduleId).HasColumnName("ScheduleId");
        this.Property(o => o.SessionID).HasColumnName("SessionID");
        this.Property(o => o.TaskCompletedOnUtc).HasColumnName("TaskCompletedOnUtc");
        this.Property(o => o.TaskDetailID).HasColumnName("TaskDetailID");
        this.Property(o => o.TaskScheduledOn).HasColumnName("TaskScheduledOn");
        this.Property(o => o.TaskStartedOnUtc).HasColumnName("TaskStartedOnUtc");
        this.Property(o => o.TaskStatus).HasColumnName("TaskStatus");
        this.Property(o => o.TaskSummary).HasColumnName("TaskSummary");
    }
}

public partial class WarehouseAPIContext : DbContext
{
    public WarehouseAPIContext() : base("name=WarehouseAPIContext")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new TaskDetailMapper());
    }
}

public class TaskDetailRepository:APIRepository<TaskDetail>
{
    WarehouseAPIContext _context;

    public TaskDetailRepository(WarehouseAPIContext context):base(context)
    {
        _context = context;
    }

    public TaskDetail UpdateTaskStartingTime(TaskDetail entity)
    {
        try
        {
            var taskDetail = new TaskDetail() { TaskStartedOnUtc = entity.TaskStartedOnUtc, TaskStatus = entity.TaskStatus,SessionID = entity.SessionID, TaskDetailID = entity.TaskDetailID };

             dbSet.Attach(taskDetail);    // THROWS THE ERROR
            _context.Entry(taskDetail).Property(x => x.TaskStartedOnUtc).IsModified = true;
            _context.SaveChanges();

            return entity;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

public class APIRepository<T> where T:class
{
        internal WarehouseAPIContext wContext;
        internal DbSet<T> dbSet;

        public APIRepository(WarehouseAPIContext context)
        {
            wContext = context;
            dbSet = context.Set<T>();
        }

        public virtual T Update(T entity)
        {
            try
            {
                var entry = wContext.Entry(entity);
                dbSet.Attach(entity);
                entry.State = EntityState.Modified;
                wContext.SaveChanges();
                return entity;
            }
            catch (Exception ex)
            {
                //ExceptionHandler.Handle(ex);
                return null;
            }
        }
}
1
  • Is that entity already available in the context cache? Are you loading that entity from database in some other place in the same context? Also why two context objects - dbSet and _context. I think, when you use .Entry, you can skip the .Attach part Commented Jan 30, 2017 at 0:06

1 Answer 1

1

There is two ways to do this, either first load the entity you want to update copy the changes to this entity and save changes, which I prefer, the second option is to load the entity you want to update, then de attach it, and attach it back , finally save the context changes.

you cannot attach an already attached entity, EF will insert the object again

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.