Esempio n. 1
0
        public void Add_SomeEntity_EntityIsAdded()
        {
            _efCoreDbContext.GetDbSet <Person>().Add(new Person());

            _dbContext.Persons.Local.Should().HaveCount(1);
            _dbContext.Entry(_dbContext.Persons.Local.First()).State.Should().Be(EntityState.Added);
        }
Esempio n. 2
0
        public void DetectChanges_PlainObject()
        {
            using (var db = new TestDbContext()) {
                var customer = new Customer {
                    Address = new Address {
                        Street = "Street 1"
                    }
                };
                db.Add(customer);
                db.SaveChanges();

                // Note: changing tracking does not work without reloading. This might be an issue with EF Core itself?
                db.Entry(customer).State = EntityState.Detached;
                customer = db.Customers.Find(customer.Id);

                Assert.AreEqual(EntityState.Unchanged, db.Entry(customer).State, "Precondition: entity is marked as unchanged");

                customer.Address.Street = "Street 2";

                db.ChangeTracker.DetectChanges();

                Assert.AreEqual(EntityState.Modified, db.Entry(customer).State, "Entity is marked as modified");
                Assert.IsTrue(db.Entry(customer).Property(m => m.Address).IsModified, "Property is marked as modified");
            }
        }
Esempio n. 3
0
 public virtual void Delete(TEntity entityToDelete)
 {
     if (context.Entry(entityToDelete).State == EntityState.Detached)
     {
         dbSet.Attach(entityToDelete);
     }
     dbSet.Remove(entityToDelete);
 }
Esempio n. 4
0
        public virtual void Delete(TEntity entityToDelete)
        {
            if (_context.Entry(entityToDelete).State == EntityState.Detached)
            {
                _context.Set <TEntity>().Attach(entityToDelete);
            }

            _context.Set <TEntity>().Remove(entityToDelete);
        }
Esempio n. 5
0
        public async Task <IActionResult> PostProduct([FromBody] Product product)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.Entry(product).State = EntityState.Added;
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetProduct", new { id = product.Id }, product));
        }
Esempio n. 6
0
 /// <summary>
 /// 更新一条记录
 /// </summary>
 /// <param name="entity">实体模型</param>
 /// <returns>bool</returns>
 public bool Update(T entity)
 {
     try
     {
         db.Set <T>().Attach(entity);
         db.Entry(entity).State = EntityState.Modified;
         return(db.SaveChanges() > 0);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Esempio n. 7
0
 public bool Create(PermissionType model)
 {
     try
     {
         _context.Entry(model).State = Microsoft.EntityFrameworkCore.EntityState.Added;
         _context.SaveChanges();
     }
     catch (Exception ex)
     {
         return(false);
     }
     return(true);
 }
Esempio n. 8
0
    public void HandleTenantNotSetWhenUpdating()
    {
        try
        {
            _connection.Open();
            var tenant1 = new TenantContext("abc", "abc", "abc",
                                            "DataSource=testdb.db", null, null);

            // TenantNotSetMode.Throw
            using (var db = new TestDbContext(tenant1, _options))
            {
                db.Database.EnsureDeleted();
                db.Database.EnsureCreated();

                var blog1 = new Blog {
                    Title = "abc"
                };
                db.Blogs.Add(blog1);
                db.SaveChanges();

                db.TenantNotSetMode = TenantNotSetMode.Throw;
                db.Entry(blog1).Property("TenantId").CurrentValue = null;

                var e = Assert.Throws <MultiTenantException>(() => db.SaveChanges());
            }

            // TenantNotSetMode.Overwrite
            using (var db = new TestDbContext(tenant1, _options))
            {
                db.Database.EnsureDeleted();
                db.Database.EnsureCreated();

                var blog1 = new Blog {
                    Title = "abc12"
                };
                db.Blogs.Add(blog1);
                db.SaveChanges();

                db.TenantNotSetMode = TenantNotSetMode.Overwrite;
                db.Entry(blog1).Property("TenantId").CurrentValue = null;
                db.SaveChanges();

                Assert.Equal(tenant1.Id, db.Entry(blog1).Property("TenantId").CurrentValue);
            }
        }
        finally
        {
            _connection.Close();
        }
    }
        public void CanCascade_UnmodifiedDifferentType()
        {
            using var dbContext = new TestDbContext();
            var subject = CreateSubject();
            var entity  = new TestModel {
                Property1 = 1
            };

            dbContext.Add(entity);
            var previousTriggerContextDescriptor = new TriggerContextDescriptor(dbContext.Entry(entity), ChangeType.Added);

            var result = subject.CanCascade(dbContext.Entry(entity), ChangeType.Modified, previousTriggerContextDescriptor);

            Assert.Equal(CanCascadeUnmodifiedExpectedOutcome, result);
        }
Esempio n. 10
0
        public void ShouldSupportNullValuesInTree()
        {
            var node1 = new TestNode
            {
                Title = "New Node",
                OneToOneOwned = null
            };

            using (var context = new TestDbContext())
            {
                context.Nodes.Add(node1);
                context.SaveChanges();
            } // Simulate detach

            using (var context = new TestDbContext())
            {
                // Setup mapping
                node1 = context.UpdateGraph(node1, map => map
                    .OwnedEntity(p => p.OneToOneOwned, with =>
                        with.OwnedEntity(p => p.OneToOneOneToOneOwned)));

                context.SaveChanges();
                context.Entry(node1).Reload();
                Assert.IsTrue(node1.OneToOneOwned == null);
            }
        }
Esempio n. 11
0
        public void ShouldSupportMultipleKeys()
        {
            var model = new MultiKeyModel
            {
                Title    = "Hello",
                Date     = DateTime.Now,
                KeyPart1 = "A123",
                KeyPart2 = "A234"
            };

            using (var context = new TestDbContext())
            {
                context.MultiKeyModels.Add(model);
                context.SaveChanges();
            } // simulate detach

            model.Date = DateTime.Parse("01/01/2010");
            using (var context = new TestDbContext())
            {
                model = context.UpdateGraph(model);
                context.SaveChanges();

                context.Entry(model).Reload();
                Assert.IsTrue(model.Date == DateTime.Parse("01/01/2010"));
            }
        }
Esempio n. 12
0
        public async Task <Product> Update(Product product)
        {
            _context.Entry(product).State = EntityState.Modified;
            await _context.SaveChangesAsync();

            return(product);
        }
Esempio n. 13
0
        public void ShouldSupportMultipleKeys()
        {
            var model = new MultiKeyModel
            {
                Title = "Hello",
                Date = DateTime.Now,
                KeyPart1 = "A123",
                KeyPart2 = "A234"
            };

            using (var context = new TestDbContext())
            {
                context.MultiKeyModels.Add(model);
                context.SaveChanges();
            } // simulate detach

            model.Date = DateTime.Parse("01/01/2010");
            using (var context = new TestDbContext())
            {
                model = context.UpdateGraph(model);
                context.SaveChanges();

                context.Entry(model).Reload();
                Assert.IsTrue(model.Date == DateTime.Parse("01/01/2010"));
            }
        }
Esempio n. 14
0
        public void ShouldSupportNullValuesInTree()
        {
            var node1 = new TestNode
            {
                Title         = "New Node",
                OneToOneOwned = null
            };

            using (var context = new TestDbContext())
            {
                context.Nodes.Add(node1);
                context.SaveChanges();
            } // Simulate detach

            using (var context = new TestDbContext())
            {
                // Setup mapping
                node1 = context.UpdateGraph(node1, map => map
                                            .OwnedEntity(p => p.OneToOneOwned, with =>
                                                         with.OwnedEntity(p => p.OneToOneOneToOneOwned)));

                context.SaveChanges();
                context.Entry(node1).Reload();
                Assert.IsTrue(node1.OneToOneOwned == null);
            }
        }
        public async Task <IActionResult> PutConfirmationResponse(int id, ConfirmationResponse confirmationResponse)
        {
            if (id != confirmationResponse.Id)
            {
                return(BadRequest());
            }

            _context.Entry(confirmationResponse).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ConfirmationResponseExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Esempio n. 16
0
        public async Task <IActionResult> PutEmployee(int id, Employee employee)
        {
            if (id != employee.EmployeeId)
            {
                return(BadRequest());
            }

            _context.Entry(employee).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EmployeeExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Esempio n. 17
0
        public async Task <int> UpdateEmployee(Employee employee)
        {
            var _employee = _context.Employees.Where(e => e.Id == employee.Id).FirstOrDefaultAsync();

            if (_employee != null)
            {
                _context.Entry(employee).State = EntityState.Detached;
            }
            else
            {
                return(0);
            }

            _context.Entry(employee).State = EntityState.Modified;
            return(await _context.SaveChangesAsync());
        }
        public IHttpActionResult PutTestTable1(int id, TestTable1 testTable1)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != testTable1.Id)
            {
                return(BadRequest());
            }

            db.Entry(testTable1).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TestTable1Exists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
        public async Task <IActionResult> PutUsuarios(int id, Usuarios usuarios)
        {
            if (id != usuarios.Id)
            {
                return(BadRequest());
            }

            _context.Entry(usuarios).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UsuariosExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Esempio n. 20
0
        public IHttpActionResult PutProduct(int id, Product product)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != product.Id)
            {
                return(BadRequest());
            }

            db.Entry(product).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Esempio n. 21
0
        public async Task Post(ResourceEditDto dto)
        {
            if (TryValidateModel(dto))
            {
                using (var db = new TestDbContext())
                {
                    var model = await db.Resources.FirstOrDefaultAsync(x => x.Id == dto.Id);

                    if (model != null)
                    {
                        _mapper.Map(dto, model);
                        model.UpdatedOnUtc    = DateTime.Now;
                        db.Entry(model).State = EntityState.Modified;
                        await db.SaveChangesAsync();
                    }
                    else
                    {
                        model = _mapper.Map <Resource>(dto);
                        model.CreatedOnUtc = DateTime.Now;
                        model.UpdatedOnUtc = DateTime.Now;
                        db.Resources.Add(model);
                        await db.SaveChangesAsync();
                    }
                }
            }
            else
            {
                throw new Exception(String.Join(";", ModelState.Values.SelectMany(v => v.Errors).Select(x => x.ErrorMessage)));
            }
        }
Esempio n. 22
0
        public void Attached_OwnedCollectionRemove()
        {
            Models.Company company1;
            using (var context = new TestDbContext(_connection))
            {
                company1 = context.Companies
                           .Include(p => p.Contacts.Select(m => m.Infos))
                           .Single(p => p.Id == 2);
                //} // Simulate detach

                //company1.Contacts.Remove(company1.Contacts.First());
                context.Entry(company1.Contacts.First()).State = EntityState.Deleted;


                //using (var context = new TestDbContext(_connection))
                //{
                // Setup mapping
                //context.Entry(company1).State = EntityState.Modified;
                context.UpdateGraph(company1, map => map
                                    .OwnedCollection(p => p.Contacts, with => with
                                                     .OwnedCollection(p => p.Infos)));

                context.SaveChanges();
                Assert.IsTrue(context.Companies
                              .Include(p => p.Contacts.Select(m => m.Infos))
                              .Single(p => p.Id == 2)
                              .Contacts.Count == 0);
            }
        }
Esempio n. 23
0
 public async Task <IActionResult> Put([FromODataUri] int key, Supplier update)
 {
     if (!ModelState.IsValid)
     {
         return(BadRequest(ModelState));
     }
     if (key != update.Id)
     {
         return(BadRequest());
     }
     db.Entry(update).State = EntityState.Modified;
     try
     {
         await db.SaveChangesAsync();
     }
     catch (DbUpdateConcurrencyException)
     {
         if (!SupplierExists(key))
         {
             return(NotFound());
         }
         else
         {
             throw;
         }
     }
     return(Updated(update));
 }
Esempio n. 24
0
        public async Task <IActionResult> PutProduct(int id, Product product)
        {
            if (id != product.Id)
            {
                return(BadRequest());
            }

            _context.Entry(product).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Esempio n. 25
0
        public void Type_IsNotEmpty()
        {
            using var dbContext = new TestDbContext();
            var sample1 = new TestModel();
            var subject = new TriggerContext <object>(dbContext.Entry(sample1).Entity, dbContext.Entry(sample1).OriginalValues, ChangeType.Modified);

            Assert.Equal(ChangeType.Modified, subject.ChangeType);
        }
Esempio n. 26
0
        public void Entity_IsNeverEmpty()
        {
            using var dbContext = new TestDbContext();
            var sample1 = new TestModel();
            var subject = new TriggerContext <object>(dbContext.Entry(sample1).Entity, dbContext.Entry(sample1).OriginalValues, default);

            Assert.NotNull(subject.Entity);
        }
Esempio n. 27
0
        public void UnmodifiedEntity_WhenTypeModified_IsNotEmpty()
        {
            using var dbContext = new TestDbContext();
            var sample1 = new TestModel();
            var subject = new TriggerContext <object>(dbContext.Entry(sample1).Entity, dbContext.Entry(sample1).OriginalValues, ChangeType.Modified, new());

            Assert.NotNull(subject.UnmodifiedEntity);
        }
Esempio n. 28
0
 public void delete(PlayList t)
 {
     using (TestDbContext context = new TestDbContext())
     {
         context.PlayLists.Attach(t);
         context.Entry(t).State = EntityState.Deleted;
         context.SaveChanges();
     }
 }
        public void CaptureDiscoveredChangesAfterAdd_DetachedEntry_RemovesDiscoveredChange()
        {
            using var dbContext = new TestDbContext();
            var subject = new TriggerContextTracker(dbContext.ChangeTracker, new EntityAndTypeCascadeStrategy());

            var testModel = new TestModel();

            dbContext.Entry(testModel).State = EntityState.Added;

            var disoveredChanges = subject.DiscoverChanges();

            Assert.Single(disoveredChanges);
            Assert.Single(subject.DiscoveredChanges);

            dbContext.Entry(testModel).State = EntityState.Detached;
            subject.CaptureChanges();
            Assert.Empty(subject.DiscoveredChanges);
        }
 public void Update(Person person)
 {
     using (TestDbContext context = new TestDbContext())
     {
         context.Person.Attach(person);
         context.Entry(person).State = System.Data.EntityState.Modified;
         context.SaveChanges();
     }
 }
Esempio n. 31
0
 public IActionResult Edit([Bind(include: "Id,Name,Password,Profile,Cv")] Test test)
 {
     if (ModelState.IsValid)
     {
         context.Entry(test).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
     }
     context.SaveChanges();
     return(RedirectToAction("AddStudent"));
 }
Esempio n. 32
0
 public void delete(UserMessage t)
 {
     using (TestDbContext context = new TestDbContext())
     {
         context.UserMessages.Attach(t);
         context.Entry(t).State = EntityState.Deleted;
         context.SaveChanges();
     }
 }