예제 #1
0
        /// <summary>
        /// 更新实体部分属性
        /// </summary>
        /// <param name="entity">实体</param>
        /// <param name="autoSave">是否立即执行保存</param>
        /// <param name="updatedProperties">要更新的字段</param>
        /// <returns></returns>
        public bool Update(T entity, bool autoSave = true, params Expression <Func <T, object> >[] updatedProperties)
        {
            int row = 0;

            //告诉EF Core开始跟踪实体的更改,
            //因为调用DbContext.Attach方法后,EF Core会将实体的State值
            //更改回EntityState.Unchanged,
            _dbContext.Attach(entity);
            if (updatedProperties.Any())
            {
                foreach (var property in updatedProperties)
                {
                    //告诉EF Core实体的属性已经更改。将属性的IsModified设置为true后,
                    //也会将实体的State值更改为EntityState.Modified,
                    //这样就保证了下面SaveChanges的时候会将实体的属性值Update到数据库中。
                    _dbContext.Entry(entity).Property(property).IsModified = true;
                }
            }

            if (autoSave)
            {
                row = Save();
            }
            return(row > 0);
        }
예제 #2
0
 public IActionResult UpdateDoctor(Doctor doctor)
 {
     try
     {
         _context.Attach(doctor);
         _context.SaveChanges();
         return(Ok("Student został zmodyfikowany"));
     }
     catch (Exception ex)
     {
         return(BadRequest(ex.Message));
     }
 }
예제 #3
0
        public async Task <Producer> DeleteProducerAsync(int id, CancellationToken cancellationToken = default)
        {
            var prod = await _context.Producers.AsNoTracking().FirstOrDefaultAsync(x => x.ProducerId == id, cancellationToken);

            if (prod == null)
            {
                return(null);
            }
            _context.Attach(prod);
            _context.Entry(prod).State = EntityState.Deleted;
            await _context.SaveChangesAsync();

            return(prod);
        }
예제 #4
0
        public async Task <Product> DeleteProduct(int id, CancellationToken cancellationToken = default)
        {
            var product = await _context.Products.AsNoTracking().Include(x => x.Category).Include(x => x.Producer).FirstOrDefaultAsync(x => x.Id == id, cancellationToken);

            if (product == null)
            {
                return(null);
            }
            _context.Attach(product);
            _context.Entry(product).State = EntityState.Deleted;
            await _context.SaveChangesAsync(cancellationToken);

            return(product);
        }
예제 #5
0
        public async Task <Category> DeleteCategory(int id, CancellationToken cancellationToken = default)
        {
            var cat = await _context.Categories.AsNoTracking().Include(x => x.Parrent).FirstOrDefaultAsync(x => x.CategoryId == id, cancellationToken);

            if (cat == null)
            {
                return(null);
            }
            _context.Attach(cat);
            _context.Entry(cat).State = EntityState.Deleted;
            await _context.SaveChangesAsync(cancellationToken);

            return(cat);
        }
예제 #6
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            db.Attach(Student).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!StudentExists(Student.ID))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(RedirectToPage("../Crud"));
        }
예제 #7
0
        public Restaurant Update(Restaurant restaurant)
        {
            _context.Attach(restaurant).State = EntityState.Modified;
            _context.SaveChanges();

            return(restaurant);
        }
예제 #8
0
        public IActionResult UpdatePerform(DateTime date, int eventId, int artistId)
        {
            var ev = _context.Events.Where(d => d.IdEvent == eventId).First();

            if (ev == null)
            {
                return(BadRequest());
            }

            if (ev.StastDate < DateTime.Now || date < ev.StastDate || date > ev.EndDate)
            {
                return(BadRequest());
            }

            var perform = new Artist_Event
            {
                IdArtist        = artistId,
                IdEvent         = eventId,
                PerformanceDate = date
            };

            _context.Attach(perform);
            _context.Entry(perform).Property("PerformanceDate").IsModified = true;
            _context.SaveChanges();
            return(Ok(perform));
        }
예제 #9
0
        public async Task <IActionResult> UpdateSchedule([FromBody] Schedule schedule, [FromRoute] int id)
        {
            _DbContext.Attach(schedule);

            _DbContext.Schedules.Update(schedule);
            await _DbContext.SaveChangesAsync();

            return(CreatedAtAction(nameof(GetByScheduleId), new { id = schedule.Id }));
        }
예제 #10
0
        public ActionResult <string> Delete(int id)
        {
            var dt = _appDbContext.obj.Find(id);

            _appDbContext.Attach(dt);
            _appDbContext.Remove(dt);
            _appDbContext.SaveChanges();
            return($"Data that has id {id} was deleted");
        }
 public async Task UpdateAsync(Employee employee)
 {
     _myContext.Attach(employee);
     _myContext.Employees.Update(employee);
     var count = await _myContext.SaveChangesAsync();
     if (count != 1)
     {
         throw new Exception("修改失败");
     }
 }
예제 #12
0
        public async Task AddEventAsync(GameEvent gameEvent)
        {
            var gameHandler = await LoadGameHandler();

            var version = gameHandler.Events.Count;

            gameHandler.AddEvent(gameEvent);

            _context.MatchEvents.Add(
                new MatchEvent
            {
                Event = JsonConvert.SerializeObject(gameEvent,
                                                    new JsonSerializerSettings {
                    TypeNameHandling = TypeNameHandling.Objects
                }),
                MatchId = _matchId,
                Version = version
            });

            var matchInfo = gameHandler.CurrentState.ToMatchInfo();

            matchInfo.MatchId = _matchId;
            matchInfo.UserId  = _userId;

            if (await _context.MatchInfos.AnyAsync(x => x.MatchId == _matchId))
            {
                var local = _context.MatchInfos.Local.FirstOrDefault(x => x.MatchId == _matchId);

                if (local != null)
                {
                    _context.Entry(local).State = EntityState.Detached;
                }

                _context.Attach(matchInfo).State = EntityState.Modified;
            }
            else
            {
                _context.MatchInfos.Add(matchInfo);
            }

            await _context.SaveChangesAsync();
        }
예제 #13
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            if (Login.wanttodon == false)
            {
                using (var db = new MyDbContext())
                {
                    var entity = new User {
                        UserId = Login.userId
                    };
                    db.Attach(entity);
                    entity.wanttodonate = true;
                    db.SaveChanges();
                }
            }
            button = true;
            var dialog = new MessageDialog("You are now not visible as a Donor");
            await dialog.ShowAsync();

            Frame.Navigate(typeof(SettingsPage));
        }
예제 #14
0
 public async Task<OrderProduct> CreateOrderProduct(int quantity, int orderId, int productId, CancellationToken cancellationToken = default)
 {
     var product = await _context.Products.FirstOrDefaultAsync(x => x.Id == productId, cancellationToken);
     var order = await _context.Orders.FirstOrDefaultAsync(x => x.OrderId == orderId, cancellationToken);
     if(product == null || order == null)
     {
         return null;
     }
     var orderProduct = await _context.OrderProducts.AsNoTracking().FirstOrDefaultAsync(x => x.Product == product || x.Order == order || x.Quantity == quantity, cancellationToken);
     if(orderProduct!=null)
     {
         return null;
     }
     orderProduct = new OrderProduct(quantity, product, order);
     _context.Add(orderProduct);
     _context.Attach(order);
     order.SumPrice = order.SumPrice + (product.Price * quantity);
     await _context.SaveChangesAsync(cancellationToken);
     return orderProduct;
 }
예제 #15
0
 public Task Save(T entity)
 {
     Context.Attach(entity);
     return(Context.SaveChangesAsync());
 }