示例#1
0
 public void Delete(T t)
 {
     if (t is SoftDeletable deletable)
     {
         deletable.IsDeleted = true;
         _prandoDbContext.Update(deletable);
     }
     else
     {
         _prandoDbContext.Set <T>().Remove(t);
     }
 }
示例#2
0
        public static void AddOrUpdate(this Microsoft.EntityFrameworkCore.DbContext ctx, object entity)
        {
            var entry = ctx.Entry(entity);

            switch (entry.State)
            {
            case EntityState.Detached:
                ctx.Add(entity);
                break;

            case EntityState.Modified:
                ctx.Update(entity);
                break;

            case EntityState.Added:
                ctx.Add(entity);
                break;

            case EntityState.Unchanged:
                //item already in db no need to do anything
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        public async Task Can_add_update_delete_end_to_end_using_partial_shadow_state()
        {
            IMutableModel model = new Model();

            var customerType = model.AddEntityType(typeof(Customer));
            var property1    = customerType.AddProperty("Id", typeof(int));

            customerType.SetPrimaryKey(property1);
            customerType.AddProperty("Name", typeof(string));

            var optionsBuilder = new DbContextOptionsBuilder()
                                 .UseModel(model.FinalizeModel())
                                 .UseInMemoryDatabase(nameof(ShadowStateUpdateTest))
                                 .UseInternalServiceProvider(_fixture.ServiceProvider);

            var customer = new Customer
            {
                Id = 42
            };

            using (var context = new DbContext(optionsBuilder.Options))
            {
                context.Add(customer);

                context.Entry(customer).Property("Name").CurrentValue = "Daenerys";

                await context.SaveChangesAsync();

                context.Entry(customer).Property("Name").CurrentValue = "Changed!";
            }

            using (var context = new DbContext(optionsBuilder.Options))
            {
                var customerFromStore = context.Set <Customer>().Single();

                Assert.Equal(42, customerFromStore.Id);
                Assert.Equal(
                    "Daenerys",
                    (string)context.Entry(customerFromStore).Property("Name").CurrentValue);
            }

            using (var context = new DbContext(optionsBuilder.Options))
            {
                var customerEntry = context.Entry(customer).GetInfrastructure();
                customerEntry[customerType.FindProperty("Name")] = "Daenerys Targaryen";

                context.Update(customer);

                await context.SaveChangesAsync();
            }

            using (var context = new DbContext(optionsBuilder.Options))
            {
                var customerFromStore = context.Set <Customer>().Single();

                Assert.Equal(42, customerFromStore.Id);
                Assert.Equal(
                    "Daenerys Targaryen",
                    (string)context.Entry(customerFromStore).Property("Name").CurrentValue);
            }

            using (var context = new DbContext(optionsBuilder.Options))
            {
                context.Remove(customer);

                await context.SaveChangesAsync();
            }

            using (var context = new DbContext(optionsBuilder.Options))
            {
                Assert.Equal(0, context.Set <Customer>().Count());
            }
        }
        public async Task Can_add_update_delete_end_to_end()
        {
            var serviceProvider = new ServiceCollection()
                                  .AddEntityFrameworkInMemoryDatabase()
                                  .AddSingleton <ILoggerFactory>(new ListLoggerFactory())
                                  .AddSingleton(TestModelSource.GetFactory(OnModelCreating))
                                  .BuildServiceProvider();

            var options = new DbContextOptionsBuilder()
                          .UseInternalServiceProvider(serviceProvider)
                          .UseInMemoryDatabase(nameof(DatabaseInMemoryTest))
                          .Options;

            var customer = new Customer
            {
                Id   = 42,
                Name = "Theon"
            };

            using (var context = new DbContext(options))
            {
                context.Add(customer);

                await context.SaveChangesAsync();

                customer.Name = "Changed!";
            }

            using (var context = new DbContext(options))
            {
                var customerFromStore = context.Set <Customer>().Single();

                Assert.Equal(42, customerFromStore.Id);
                Assert.Equal("Theon", customerFromStore.Name);
            }

            using (var context = new DbContext(options))
            {
                customer.Name = "Theon Greyjoy";
                context.Update(customer);

                await context.SaveChangesAsync();
            }

            using (var context = new DbContext(options))
            {
                var customerFromStore = context.Set <Customer>().Single();

                Assert.Equal(42, customerFromStore.Id);
                Assert.Equal("Theon Greyjoy", customerFromStore.Name);
            }

            using (var context = new DbContext(options))
            {
                context.Remove(customer);

                await context.SaveChangesAsync();
            }

            using (var context = new DbContext(options))
            {
                Assert.Equal(0, context.Set <Customer>().Count());
            }
        }
示例#5
0
        public async Task It_throws_object_disposed_exception(bool async)
        {
            var context = new DbContext(new DbContextOptions <DbContext>());

            if (async)
            {
                await context.DisposeAsync();
            }
            else
            {
                context.Dispose();
            }

            // methods (tests all paths)
            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                Assert.Throws <ObjectDisposedException>(() => context.Add(new object())).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                Assert.Throws <ObjectDisposedException>(() => context.Find(typeof(Random), 77)).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                Assert.Throws <ObjectDisposedException>(() => context.Attach(new object())).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                Assert.Throws <ObjectDisposedException>(() => context.Update(new object())).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                Assert.Throws <ObjectDisposedException>(() => context.Remove(new object())).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                Assert.Throws <ObjectDisposedException>(() => context.SaveChanges()).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                (await Assert.ThrowsAsync <ObjectDisposedException>(() => context.SaveChangesAsync())).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                (await Assert.ThrowsAsync <ObjectDisposedException>(() => context.AddAsync(new object()).AsTask())).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                (await Assert.ThrowsAsync <ObjectDisposedException>(() => context.FindAsync(typeof(Random), 77).AsTask())).Message);

            var methodCount         = typeof(DbContext).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Count();
            var expectedMethodCount = 42 + 8;

            Assert.True(
                methodCount == expectedMethodCount,
                userMessage: $"Expected {expectedMethodCount} methods on DbContext but found {methodCount}. "
                + "Update test to ensure all methods throw ObjectDisposedException after dispose.");

            // getters
            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                Assert.Throws <ObjectDisposedException>(() => context.ChangeTracker).Message);

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                Assert.Throws <ObjectDisposedException>(() => context.Model).Message);

            var expectedProperties = new List <string>
            {
                nameof(DbContext.ChangeTracker),
                nameof(DbContext.ContextId), // By-design, does not throw for disposed context
                nameof(DbContext.Database),
                nameof(DbContext.Model)
            };

            Assert.True(
                expectedProperties.SequenceEqual(
                    typeof(DbContext)
                    .GetProperties()
                    .Select(p => p.Name)
                    .OrderBy(s => s)
                    .ToList()),
                userMessage: "Unexpected properties on DbContext. "
                + "Update test to ensure all getters throw ObjectDisposedException after dispose.");

            Assert.StartsWith(
                CoreStrings.ContextDisposed,
                Assert.Throws <ObjectDisposedException>(() => ((IInfrastructure <IServiceProvider>)context).Instance).Message);
        }
示例#6
0
        public async Task Can_add_update_delete_end_to_end_using_partial_shadow_state()
        {
            var modelBuilder      = InMemoryTestHelpers.Instance.CreateConventionBuilder();
            var entityTypeBuilder = modelBuilder.Entity <Customer>();

            entityTypeBuilder.Property <string>("Name");

            var customerType = (IEntityType)entityTypeBuilder.Metadata;

            var optionsBuilder = new DbContextOptionsBuilder()
                                 .UseModel(modelBuilder.FinalizeModel())
                                 .UseInMemoryDatabase(nameof(ShadowStateUpdateTest))
                                 .UseInternalServiceProvider(_fixture.ServiceProvider);

            var customer = new Customer {
                Id = 42
            };

            using (var context = new DbContext(optionsBuilder.Options))
            {
                context.Add(customer);

                context.Entry(customer).Property("Name").CurrentValue = "Daenerys";

                await context.SaveChangesAsync();

                context.Entry(customer).Property("Name").CurrentValue = "Changed!";
            }

            using (var context = new DbContext(optionsBuilder.Options))
            {
                var customerFromStore = context.Set <Customer>().Single();

                Assert.Equal(42, customerFromStore.Id);
                Assert.Equal(
                    "Daenerys",
                    (string)context.Entry(customerFromStore).Property("Name").CurrentValue);
            }

            using (var context = new DbContext(optionsBuilder.Options))
            {
                var customerEntry = context.Entry(customer).GetInfrastructure();
                customerEntry[customerType.FindProperty("Name")] = "Daenerys Targaryen";

                context.Update(customer);

                await context.SaveChangesAsync();
            }

            using (var context = new DbContext(optionsBuilder.Options))
            {
                var customerFromStore = context.Set <Customer>().Single();

                Assert.Equal(42, customerFromStore.Id);
                Assert.Equal(
                    "Daenerys Targaryen",
                    (string)context.Entry(customerFromStore).Property("Name").CurrentValue);
            }

            using (var context = new DbContext(optionsBuilder.Options))
            {
                context.Remove(customer);

                await context.SaveChangesAsync();
            }

            using (var context = new DbContext(optionsBuilder.Options))
            {
                Assert.Equal(0, context.Set <Customer>().Count());
            }
        }
示例#7
0
        private void Can_add_update_delete_end_to_end <T>()
            where T : class, new()
        {
            var type  = typeof(T);
            var model = new Model();

            var entityType   = model.AddEntityType(type);
            var idProperty   = entityType.AddProperty("Id", typeof(int));
            var nameProperty = entityType.AddProperty("Name", typeof(string));

            entityType.GetOrSetPrimaryKey(idProperty);

            var optionsBuilder = new DbContextOptionsBuilder()
                                 .UseModel(model)
                                 .UseInMemoryDatabase(nameof(EndToEndTest))
                                 .UseInternalServiceProvider(_fixture.ServiceProvider);

            T entity;

            using (var context = new DbContext(optionsBuilder.Options))
            {
                var entry = context.ChangeTracker.GetInfrastructure().GetOrCreateEntry(new T());
                entity = (T)entry.Entity;

                entry[idProperty]   = 42;
                entry[nameProperty] = "The";

                entry.SetEntityState(EntityState.Added);

                context.SaveChanges();
            }

            using (var context = new DbContext(optionsBuilder.Options))
            {
                var entityFromStore = context.Set <T>().Single();
                var entityEntry     = context.Entry(entityFromStore);

                Assert.NotSame(entity, entityFromStore);
                Assert.Equal(42, entityEntry.Property(idProperty.Name).CurrentValue);
                Assert.Equal("The", entityEntry.Property(nameProperty.Name).CurrentValue);

                entityEntry.GetInfrastructure()[nameProperty] = "A";

                context.Update(entityFromStore);

                context.SaveChanges();
            }

            using (var context = new DbContext(optionsBuilder.Options))
            {
                var entityFromStore = context.Set <T>().Single();
                var entry           = context.Entry(entityFromStore);

                Assert.Equal("A", entry.Property(nameProperty.Name).CurrentValue);

                context.Remove(entityFromStore);

                context.SaveChanges();
            }

            using (var context = new DbContext(optionsBuilder.Options))
            {
                Assert.Equal(0, context.Set <T>().Count());
            }
        }