Ejemplo n.º 1
0
        public async Task <bool> UpdateAsync(Department paraObject)
        {
            Department item = await context.Department
                              .AsNoTracking()
                              .FirstOrDefaultAsync(x => x.DepartmentId == paraObject.DepartmentId);

            if (item == null)
            {
                return(false);
            }
            else
            {
                context.CleanAllEFCoreTracking <Department>();
                context.Entry(paraObject).State = EntityState.Modified;

                // save
                await context.SaveChangesAsync();

                return(true);
            }
        }
Ejemplo n.º 2
0
        public async Task <bool> UpdateAsync(Person paraObject)
        {
            #region EF Core 追蹤查詢所造成的問題說明
            // 若再進行搜尋該修改紀錄的時候,使用了 追蹤查詢 (也就是,沒有使用 .AsNoTracking()方法)
            // 將會造成快取記錄在電腦端,而這裡若要進行
            // context.Entry(paraObject).State = EntityState.Modified; 呼叫與更新的時候
            // 將會造成問題
            // System.InvalidOperationException: The instance of entity type 'Person' cannot be tracked
            // because another instance with the same key value for {'PersonId'} 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.
            #endregion

            Person item = await context.Person
                          .AsNoTracking()
                          .FirstOrDefaultAsync(x => x.PersonId == paraObject.PersonId);

            if (item == null)
            {
                return(false);
            }
            else
            {
                #region 在這裡需要設定需要解除快取紀錄
                context.CleanAllEFCoreTracking <Person>();
                #endregion
                // set Modified flag in your entry
                context.Entry(paraObject).State = EntityState.Modified;

                // save
                await context.SaveChangesAsync();

                return(true);
            }
        }