当前位置: 首页>>代码示例>>C#>>正文


C# DbContext.Add方法代码示例

本文整理汇总了C#中DbContext.Add方法的典型用法代码示例。如果您正苦于以下问题:C# DbContext.Add方法的具体用法?C# DbContext.Add怎么用?C# DbContext.Add使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在DbContext的用法示例。


在下文中一共展示了DbContext.Add方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Run

        public static void Run(DbContext db)
        {
            if (!db.Set<Profile>().Any())
                db.Add(new Profile
                {
                    Name = "Alexandre Machado",
                    Email = "[email protected]",
                    Login = "cwinet\alexandrelima"
                });
            if (!db.Set<Skill>().Any())
                db.AddRange(
                    new Skill { SkillName = "ASP.NET" },
                    new Skill { SkillName = "Ruby" },
                    new Skill { SkillName = "JavaScript" }
                    );
            if (!db.Set<Mastery>().Any())
                db.AddRange(
                    new Mastery { Code = 10, Name = "Iniciante", Description = "recordação não-situacional, reconhecimento decomposto, decisão analítica, consciência monitorada" },
                    new Mastery { Code = 20, Name = "Competente", Description = "recordação situacional, reconhecimento decomposto, decisão analítica, consciência monitorada" },
                    new Mastery { Code = 30, Name = "Proeficiente", Description = "recordação situacional, reconhecimento holítico, decisão analítica, consciência monitorada" },
                    new Mastery { Code = 40, Name = "Experiente", Description = "recordação situacional, reconhecimento holítico, decisão intuitiva, consciência monitorada" },
                    new Mastery { Code = 50, Name = "Mestre", Description = "recordação situacional, reconhecimento holítico, decisão intuitiva, consciência absorvida" });

            db.SaveChanges();
        }
开发者ID:Alexandre-Machado,项目名称:SkillMap,代码行数:25,代码来源:Seed.cs

示例2: PopulateData

        private static void PopulateData(DbContext context, DateTime latestAlbumDate)
        {
            var albums = TestAlbumDataProvider.GetAlbums(latestAlbumDate);

            foreach (var album in albums)
            {
                context.Add(album);
            }

            context.SaveChanges();
        }
开发者ID:Estefani1,项目名称:MusicStore,代码行数:11,代码来源:AnnouncementComponentTest.cs

示例3: It_throws_object_disposed_exception

        public async void It_throws_object_disposed_exception()
        {
            var context = new DbContext(new DbContextOptions<DbContext>());
            context.Dispose();

            // methods (tests all paths)
            Assert.Throws<ObjectDisposedException>(() => context.Add(new object()));
            Assert.Throws<ObjectDisposedException>(() => context.Attach(new object()));
            Assert.Throws<ObjectDisposedException>(() => context.Update(new object()));
            Assert.Throws<ObjectDisposedException>(() => context.Remove(new object()));
            Assert.Throws<ObjectDisposedException>(() => context.SaveChanges());
            await Assert.ThrowsAsync<ObjectDisposedException>(() => context.SaveChangesAsync());

            var methodCount = typeof(DbContext).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Count();
            var expectedMethodCount = 27;
            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.Throws<ObjectDisposedException>(() => context.ChangeTracker);
            Assert.Throws<ObjectDisposedException>(() => context.Model);

            var expectedProperties = new List<string> { "ChangeTracker", "Database", "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.Throws<ObjectDisposedException>(() => ((IInfrastructure<IServiceProvider>)context).Instance);
        }
开发者ID:adwardliu,项目名称:EntityFramework,代码行数:37,代码来源:DbContextTest.cs

示例4: PopulateDataForEventSignup

        private static void PopulateDataForEventSignup(DbContext context)
        {
            if (!populatedData)
            {
                var campaignEvents = TestEventModelProvider.GetEvents();

                foreach (var campaignEvent in campaignEvents)
                {
                    context.Add(campaignEvent);
                    context.Add(campaignEvent.Campaign);
                }
                context.SaveChanges();
                populatedData = true;
            }
        }
开发者ID:joelhulen,项目名称:allReady,代码行数:15,代码来源:AllReadyDataAccessEF7Tests.cs

示例5: Navigation_fixup_happens_with_compiled_metadata_using_non_standard_collection_access

        public void Navigation_fixup_happens_with_compiled_metadata_using_non_standard_collection_access()
        {
            var optionsBuilder = new DbContextOptionsBuilder()
                .UseModel(new _OneTwoThreeContextModel());
            optionsBuilder.UseInMemoryStore();

            using (var context = new DbContext(optionsBuilder.Options))
            {
                context.Add(new KoolEntity6 { Id = 11, Kool5Id = 24 });
                context.Add(new KoolEntity5 { Id = 21 });
                context.Add(new KoolEntity6 { Id = 12, Kool5Id = 24 });
                context.Add(new KoolEntity5 { Id = 22 });
                context.Add(new KoolEntity5 { Id = 23 });
                context.Add(new KoolEntity6 { Id = 13, Kool5Id = 25 });
                context.Add(new KoolEntity5 { Id = 24 });
                context.Add(new KoolEntity5 { Id = 25 });

                Assert.Equal(3, context.ChangeTracker.Entries<KoolEntity6>().Count());
                Assert.Equal(5, context.ChangeTracker.Entries<KoolEntity5>().Count());

                foreach (var entry in context.ChangeTracker.Entries<KoolEntity6>())
                {
                    var entity = entry.Entity;

                    Assert.Equal(entity.Kool5Id, entity.Kool5.Id);
                    Assert.Contains(entity, entity.Kool5.Kool6s);
                }
            }
        }
开发者ID:thegido,项目名称:EntityFramework,代码行数:29,代码来源:CompiledModelTest.cs

示例6: FixupTest

        private static void FixupTest(IModel model)
        {
            var optionsBuilder = new DbContextOptionsBuilder()
                .UseModel(model);
            optionsBuilder.UseInMemoryStore(persist: false);

            using (var context = new DbContext(optionsBuilder.Options))
            {
                var guid1 = Guid.NewGuid();
                var guid2 = Guid.NewGuid();
                var guid3 = Guid.NewGuid();

                context.Add(new KoolEntity1 { Id1 = 11, Id2 = guid1, KoolEntity2Id = 24 });
                context.Add(new KoolEntity1 { Id1 = 12, Id2 = guid2, KoolEntity2Id = 24 });
                context.Add(new KoolEntity1 { Id1 = 13, Id2 = guid3, KoolEntity2Id = 25 });

                context.Add(new KoolEntity2 { Id = 21, KoolEntity1Id1 = 11, KoolEntity1Id2 = guid1, KoolEntity3Id = 33 });
                context.Add(new KoolEntity2 { Id = 22, KoolEntity1Id1 = 11, KoolEntity1Id2 = guid1, KoolEntity3Id = 33 });
                context.Add(new KoolEntity2 { Id = 23, KoolEntity1Id1 = 11, KoolEntity1Id2 = guid1, KoolEntity3Id = 35 });
                context.Add(new KoolEntity2 { Id = 24, KoolEntity1Id1 = 12, KoolEntity1Id2 = guid2, KoolEntity3Id = 35 });
                context.Add(new KoolEntity2 { Id = 25, KoolEntity1Id1 = 12, KoolEntity1Id2 = guid2, KoolEntity3Id = 35 });

                context.Add(new KoolEntity3 { Id = 31 });
                context.Add(new KoolEntity3 { Id = 32 });
                context.Add(new KoolEntity3 { Id = 33 });
                context.Add(new KoolEntity3 { Id = 34 });
                context.Add(new KoolEntity3 { Id = 35 });

                Assert.Equal(3, context.ChangeTracker.Entries<KoolEntity1>().Count());
                Assert.Equal(5, context.ChangeTracker.Entries<KoolEntity2>().Count());
                Assert.Equal(5, context.ChangeTracker.Entries<KoolEntity3>().Count());

                foreach (var entry in context.ChangeTracker.Entries<KoolEntity1>())
                {
                    var entity = entry.Entity;

                    Assert.Equal(entity.KoolEntity2Id, entity.NavTo2.Id);
                    Assert.Contains(entity, entity.NavTo2.NavTo1s);
                }

                foreach (var entry in context.ChangeTracker.Entries<KoolEntity2>())
                {
                    var entity = entry.Entity;

                    // TODO: This broke after removing IForeignKey.ReferencingProperties
                    //Assert.Equal(entity.KoolEntity1Id1, entity.NavTo1.Id1);
                    //Assert.Equal(entity.KoolEntity1Id2, entity.NavTo1.Id2);
                    //Assert.Contains(entity, entity.NavTo1.NavTo2s);
                }
            }
        }
开发者ID:thegido,项目名称:EntityFramework,代码行数:51,代码来源:CompiledModelTest.cs

示例7: PopulateData

        private void PopulateData(DbContext context)
        {
            if (!populatedData)
            {
                var activities = TestActivityModelProvider.GetActivities();

                foreach (var activity in activities)
                {
                    context.Add(activity);
                    context.Add(activity.Campaign);
                    activitiesAdded++;
                }
                context.SaveChanges();
                populatedData = true;
            }
        }
开发者ID:rwfrago,项目名称:allReady,代码行数:16,代码来源:ActivityApiControllerTests.cs

示例8: Can_use_self_referencing_overlapping_FK_PK

            [Fact] // Issue #3376
            public virtual void Can_use_self_referencing_overlapping_FK_PK()
            {
                var modelBuilder = CreateModelBuilder();

                modelBuilder.Entity<ModifierGroupHeader>()
                    .HasKey(x => new { x.GroupHeaderId, x.AccountId });

                modelBuilder.Entity<ModifierGroupHeader>()
                    .HasOne(x => x.ModifierGroupHeader2)
                    .WithMany(x => x.ModifierGroupHeader1)
                    .HasForeignKey(x => new { x.LinkedGroupHeaderId, x.AccountId });

                var contextOptions = new DbContextOptionsBuilder()
                    .UseModel(modelBuilder.Model)
                    .UseInMemoryDatabase()
                    .Options;

                using (var context = new DbContext(contextOptions))
                {
                    var parent = context.Add(new ModifierGroupHeader { GroupHeaderId = 77, AccountId = 90 }).Entity;
                    var child1 = context.Add(new ModifierGroupHeader { GroupHeaderId = 78, AccountId = 90 }).Entity;
                    var child2 = context.Add(new ModifierGroupHeader { GroupHeaderId = 79, AccountId = 90 }).Entity;

                    child1.ModifierGroupHeader2 = parent;
                    child2.ModifierGroupHeader2 = parent;

                    context.SaveChanges();

                    AssertGraph(parent, child1, child2);
                }

                using (var context = new DbContext(contextOptions))
                {
                    var parent = context.Set<ModifierGroupHeader>().Single(e => e.GroupHeaderId == 77);
                    var child1 = context.Set<ModifierGroupHeader>().Single(e => e.GroupHeaderId == 78);
                    var child2 = context.Set<ModifierGroupHeader>().Single(e => e.GroupHeaderId == 79);

                    AssertGraph(parent, child1, child2);
                }
            }
开发者ID:RiveGauche,项目名称:EntityFramework,代码行数:41,代码来源:OneToManyTestBase.cs

示例9: Can_use_self_referencing_overlapping_FK_PK

            [Fact] // Issue #3376
            public virtual void Can_use_self_referencing_overlapping_FK_PK()
            {
                var modelBuilder = CreateModelBuilder();

                modelBuilder.Entity<Node>(b =>
                    {
                        b.HasKey(e => new { e.ListId, e.PreviousNodeId });
                        b.HasOne(e => e.NextNode)
                            .WithOne(e => e.PreviousNode)
                            .HasForeignKey<Node>(e => new { e.ListId, e.NextNodeId });
                    });

                var contextOptions = new DbContextOptionsBuilder()
                    .UseModel(modelBuilder.Model)
                    .UseInMemoryDatabase()
                    .Options;

                using (var context = new DbContext(contextOptions))
                {
                    var node1 = context.Add(new Node { ListId = 90, PreviousNodeId = 77 }).Entity;
                    var node2 = context.Add(new Node { ListId = 90, PreviousNodeId = 78 }).Entity;
                    var node3 = context.Add(new Node { ListId = 90, PreviousNodeId = 79 }).Entity;

                    node1.NextNode = node2;
                    node3.PreviousNode = node2;

                    context.SaveChanges();

                    AssertGraph(node1, node2, node3);
                }

                using (var context = new DbContext(contextOptions))
                {
                    var node1 = context.Set<Node>().Single(e => e.PreviousNodeId == 77);
                    var node2 = context.Set<Node>().Single(e => e.PreviousNodeId == 78);
                    var node3 = context.Set<Node>().Single(e => e.PreviousNodeId == 79);

                    AssertGraph(node1, node2, node3);
                }
            }
开发者ID:RickyLin,项目名称:EntityFramework,代码行数:41,代码来源:OneToOneTestBase.cs

示例10: Can_add_update_delete_end_to_end_using_partial_shadow_state

        public async Task Can_add_update_delete_end_to_end_using_partial_shadow_state()
        {
            var model = new Model();

            var customerType = new EntityType(typeof(Customer));
            customerType.SetKey(customerType.AddProperty("Id", typeof(int), shadowProperty: false, concurrencyToken: false));
            customerType.AddProperty("Name", typeof(string), shadowProperty: true, concurrencyToken: false);

            model.AddEntityType(customerType);

            var options = new DbContextOptions()
                .UseModel(model)
                .UseInMemoryStore();

            var customer = new Customer { Id = 42 };

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

                // TODO: Better API for shadow state access
                var customerEntry = context.ChangeTracker.Entry(customer).StateEntry;
                customerEntry[customerType.GetProperty("Name")] = "Daenerys";

                await context.SaveChangesAsync();

                customerEntry[customerType.GetProperty("Name")] = "Changed!";
            }

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

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

            using (var context = new DbContext(options))
            {
                var customerEntry = context.ChangeTracker.Entry(customer).StateEntry;
                customerEntry[customerType.GetProperty("Name")] = "Daenerys Targaryen";

                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(
                    "Daenerys Targaryen",
                    (string)context.ChangeTracker.Entry(customerFromStore).Property("Name").CurrentValue);
            }

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

                await context.SaveChangesAsync();
            }

            using (var context = new DbContext(options))
            {
                Assert.Equal(0, context.Set<Customer>().Count());
            }
        }
开发者ID:Nyaoso,项目名称:EntityFramework,代码行数:71,代码来源:ShadowStateUpdateTest.cs


注:本文中的DbContext.Add方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。