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


C# BloggingContext.SaveChanges方法代码示例

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


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

示例1: SaveChanges_logs_DataStoreErrorLogState

        public async Task SaveChanges_logs_DataStoreErrorLogState(bool async)
        {
            var loggerFactory = new TestLoggerFactory();
            var serviceProvider = new ServiceCollection()
                .AddEntityFramework()
                .AddInMemoryStore()
                .ServiceCollection()
                .AddInstance<ILoggerFactory>(loggerFactory)
                .BuildServiceProvider();

            using (var context = new BloggingContext(serviceProvider))
            {
                context.Blogs.Add(new BloggingContext.Blog(jimSaysThrow: false) { Url = "http://sample.com" });
                context.SaveChanges();
                context.ChangeTracker.Entries().Single().State = EntityState.Added;

                Exception ex;
                if (async)
                {
                    ex = await Assert.ThrowsAsync<ArgumentException>(() => context.SaveChangesAsync());
                }
                else
                {
                    ex = Assert.Throws<ArgumentException>(() => context.SaveChanges());
                }

                Assert.Same(ex, loggerFactory.Logger.LastDataStoreErrorException);
                Assert.Same(typeof(BloggingContext), loggerFactory.Logger.LastDataStoreErrorState.ContextType);
                Assert.EndsWith(ex.ToString(), loggerFactory.Logger.LastDataStoreErrorFormatter(loggerFactory.Logger.LastDataStoreErrorState, ex));
            }
        }
开发者ID:aishaloshik,项目名称:EntityFramework,代码行数:31,代码来源:DataStoreErrorLogStateTest.cs

示例2: AddSiteUpdate

        public bool AddSiteUpdate(string headline, string importance)
        {
            using (var db = new BloggingContext())
            {
                try
                {
                    var user = (from u in db.Users
                        where u.Username == this.User.Identity.Name
                        select u)
                        .FirstOrDefault();
                    ;

                    var update = new SiteUpdate()
                    {
                        User = user,
                        Headline = headline,
                        Importance = importance,
                        Timestamp = DateTime.Now
                    };

                    db.SiteUpdates.Add(update);
                    db.SaveChanges();
                }
                catch
                {
                    return false;
                }
            }

            return true;
        }
开发者ID:TOByrne,项目名称:TGOByrne,代码行数:31,代码来源:SiteAdminModel.cs

示例3: SetUp

 protected override void SetUp()
 {
     base.SetUp();
     using (var context = new BloggingContext(ConnectionStringEF))
     {
         context.Blogs.RemoveRange(context.Blogs);
         context.Posts.RemoveRange(context.Posts);
         context.SaveChanges();
     }
 }
开发者ID:Emill,项目名称:Npgsql,代码行数:10,代码来源:EntityFrameworkBasicTests.cs

示例4: Run

        public static void Run()
        {
            var connectionString = @"Server=(localdb)\mssqllocaldb;Database=EFSaving.Transactions;Trusted_Connection=True;";

            using (var context = new BloggingContext(
                new DbContextOptionsBuilder<BloggingContext>()
                    .UseSqlServer(connectionString)
                    .Options))
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();
            }

            var connection = new SqlConnection(connectionString);
            connection.Open();

            using (var transaction = connection.BeginTransaction())
            {
                try
                {
                    // Run raw ADO.NET command in the transaction
                    var command = connection.CreateCommand();
                    command.Transaction = transaction;
                    command.CommandText = "DELETE FROM dbo.Blogs";
                    command.ExecuteNonQuery();

                    // Run an EF Core command in the transaction
                    var options = new DbContextOptionsBuilder<BloggingContext>()
                        .UseSqlServer(connection)
                        .Options;

                    using (var context = new BloggingContext(options))
                    {
                        context.Database.UseTransaction(transaction);
                        context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet" });
                        context.SaveChanges();
                    }

                    // Commit transaction if all commands succeed, transaction will auto-rollback
                    // when disposed if either commands fails
                    transaction.Commit();
                }
                catch (System.Exception)
                {
                    // TODO: Handle failure
                }
            }
        }
开发者ID:CrazyHorse007,项目名称:EntityFramework.Docs,代码行数:48,代码来源:Sample.cs

示例5: Inserts_are_batched_correctly

        public void Inserts_are_batched_correctly(bool clientPk, bool clientFk, bool clientOrder)
        {
            var optionsBuilder = new DbContextOptionsBuilder();
            optionsBuilder.UseSqlServer(_testStore.Connection);

            var expectedBlogs = new List<Blog>();
            using (var context = new BloggingContext(_serviceProvider, optionsBuilder.Options))
            {
                context.Database.EnsureCreated();
                var owner1 = new Owner();
                var owner2 = new Owner();
                context.Owners.Add(owner1);
                context.Owners.Add(owner2);

                for (var i = 1; i < 500; i++)
                {
                    var blog = new Blog();
                    if (clientPk)
                    {
                        blog.Id = Guid.NewGuid();
                    }

                    if (clientFk)
                    {
                        blog.Owner = i % 2 == 0 ? owner1 : owner2;
                    }

                    if (clientOrder)
                    {
                        blog.Order = i;
                    }

                    context.Blogs.Add(blog);
                    expectedBlogs.Add(blog);
                }

                context.SaveChanges();
            }

            AssertDatabaseState(clientOrder, expectedBlogs, optionsBuilder);
        }
开发者ID:RickyLin,项目名称:EntityFramework,代码行数:41,代码来源:BatchingTest.cs

示例6: Batches_are_divided_correctly_with_two_inserted_columns

        public void Batches_are_divided_correctly_with_two_inserted_columns()
        {
            var optionsBuilder = new EntityOptionsBuilder();
            optionsBuilder.UseSqlServer(_testStore.Connection);

            using (var context = new BloggingContext(_serviceProvider, optionsBuilder.Options))
            {
                context.Database.EnsureCreated();

                for (var i = 1; i < 1101; i++)
                {
                    var blog = new Blog { Id = i, Name = "Foo" + i };
                    context.Blogs.Add(blog);
                }

                context.SaveChanges();
            }

            using (var context = new BloggingContext(_serviceProvider, optionsBuilder.Options))
            {
                Assert.Equal(1100, context.Blogs.Count());
            }
        }
开发者ID:aishaloshik,项目名称:EntityFramework,代码行数:23,代码来源:BatchingTest.cs

示例7: Main

        static void Main(string[] args)
        {
            using (var db = new BloggingContext())
            {
                var serviceProvider = db.GetInfrastructure<IServiceProvider>();
                var loggerFactory = serviceProvider.GetService<ILoggerFactory>();
                loggerFactory.AddProvider(new MyLoggerProvider());
            }

            using (var db = new BloggingContext())
            {
                db.Database.EnsureCreated();
                db.Blogs.Add(new Blog { Url = "http://sample.com" });
                db.SaveChanges();
            }

            using (var db = new BloggingContext())
            {
                foreach (var blog in db.Blogs)
                {
                    Console.WriteLine(blog.Url);
                }
            }
        }
开发者ID:amtruenorth,项目名称:EntityFramework.Docs,代码行数:24,代码来源:Program.cs

示例8: AddPost

        public Post AddPost(string title, string content, List<string> tags, string section = "Personal")
        {
            using (var db = new BloggingContext())
            {
                title = Sanitize(title);
                content = Sanitize(content);
                Sanitize(tags);
                section = Sanitize(section);

                var postTags = VerifyTagsInDB(tags, db);

                GetBlog(section, db);
                GetUser(db);
                GetSection(section, db);

                var time = DateTime.Now;

                var post = new Post
                {
                    Blog = _Blog,
                    BlogBlogId = _Blog.BlogId,
                    Content = content,
                    Title = title,
                    User = _User,
                    UserUserId = _User.UserId,
                    Time = time,
                    Tags = postTags,
                    Section = _Section
                };

                var newPost = db.Posts.Add(post);
                db.SaveChanges();

                return newPost;
            }
        }
开发者ID:TOByrne,项目名称:TGOByrne,代码行数:36,代码来源:PostModel.cs

示例9: TestCacheReader

        public void TestCacheReader()
        {
            // Tests all kinds of entity field types to cover ArrayDbDataReader.
            var test = GetTestEntity();

            using (var ctx = new BloggingContext(ConnectionString))
            {
                ctx.Tests.Add(test);
                ctx.SaveChanges();
            }

            // Use new context to ensure no first-level caching.
            using (var ctx = new BloggingContext(ConnectionString))
            {
                // Check default deserialization.
                var test0 = ctx.Tests.Single(x => x.Bool);
                Assert.AreEqual(test, test0);
            }
        }
开发者ID:isapego,项目名称:ignite,代码行数:19,代码来源:EntityFrameworkCacheTest.cs

示例10: InsertAndSelect

        public void InsertAndSelect()
        {
            var varbitVal = "10011";

            using (var context = new BloggingContext(ConnectionStringEF))
            {
                var blog = new Blog()
                {
                    Name = "Some blog name"
                };
                blog.Posts = new List<Post>();
                for (int i = 0; i < 5; i++)
                    blog.Posts.Add(new Post()
                    {
                        Content = "Some post content " + i,
                        Rating = (byte)i,
                        Title = "Some post Title " + i,
                        VarbitColumn = varbitVal
                    });
                context.Blogs.Add(blog);
                context.NoColumnsEntities.Add(new NoColumnsEntity());
                context.SaveChanges();
            }

            using (var context = new BloggingContext(ConnectionStringEF))
            {
                var posts = from p in context.Posts
                            select p;
                Assert.AreEqual(5, posts.Count());
                foreach (var post in posts)
                {
                    StringAssert.StartsWith("Some post Title ", post.Title);
                    Assert.AreEqual(varbitVal, post.VarbitColumn);
                }
                var someParameter = "Some";
                Assert.IsTrue(context.Posts.Any(p => p.Title.StartsWith(someParameter)));
                Assert.IsTrue(context.Posts.Select(p => p.VarbitColumn == varbitVal).First());
                Assert.IsTrue(context.Posts.Select(p => p.VarbitColumn == "10011").First());
                Assert.AreEqual(1, context.NoColumnsEntities.Count());
            }
        }
开发者ID:neisbut,项目名称:npgsql,代码行数:41,代码来源:EntityFrameworkBasicTests.cs

示例11: RemoveBlog

        internal void RemoveBlog(BloggingContext db, string username)
        {
            var blog = (from b in db.Blogs
                        where b.Name.ToLower() == username.ToLower()
                        select b).First();

            db.Blogs.Remove(blog);
            db.SaveChanges();
        }
开发者ID:TOByrne,项目名称:TGOByrne,代码行数:9,代码来源:IndexModel.cs

示例12: RemovePost

        public bool RemovePost(int postid)
        {
            using (var db = new BloggingContext())
            {
                var post = (from p in db.Posts
                            where p.PostId == postid
                            select p).FirstOrDefault();

                post.Active = "inactive";

                try
                {
                    db.SaveChanges();
                    return true;
                }
                catch
                {
                    return false;
                }
            }
        }
开发者ID:TOByrne,项目名称:TGOByrne,代码行数:21,代码来源:PostModel.cs

示例13: SelectWithLike_SpecialCharacters

		public void SelectWithLike_SpecialCharacters()
		{
			DateTime createdOnDate = new DateTime(2014, 05, 08);
			using (var context = new BloggingContext(ConnectionStringEF))
			{
				var blog = new Blog()
				{
					Name = "Special Characters Test"
				};
				blog.Posts = new List<Post>();

				blog.Posts.Add(new Post()
				{
					Content = "C:\\blog\\Some_post_title%",
					Rating = (byte)1,
					Title = "Some post Title ",
					CreationDate = createdOnDate.AddHours(1)
				});
				blog.Posts.Add(new Post()
				{
					Content = "C:\\blog\\Some_post_title\\",
					Rating = (byte)2,
					Title = "Some post Title ",
					CreationDate = createdOnDate.AddHours(2)
				});
				blog.Posts.Add(new Post()
				{
					Content = "%Test",
					Rating = (byte)3,
					Title = "Some post Title ",
					CreationDate = createdOnDate.AddHours(3)
				});
				context.Blogs.Add(blog);
				context.SaveChanges();
			}

			using (var context = new BloggingContext(ConnectionStringEF))
			{
				var posts1 = from p in context.Posts
				             where p.Content.Contains("_")
				             select p;
				Assert.AreEqual(2, posts1.Count());

				var posts2 = from p in context.Posts
				             where p.Content.EndsWith("\\")
				             select p;
				Assert.AreEqual(1, posts2.Count());

				var posts3 = from p in context.Posts
				             where p.Content.StartsWith("%")
				             select p;
				Assert.AreEqual(1, posts3.Count());
			}
		}
开发者ID:Emill,项目名称:Npgsql,代码行数:54,代码来源:EntityFrameworkBasicTests.cs

示例14: SelectWithWhere

        public void SelectWithWhere()
        {
            using (var context = new BloggingContext(ConnectionStringEF))
            {
                var blog = new Blog()
                {
                    Name = "Some blog name"
                };
                blog.Posts = new List<Post>();
                for (int i = 0; i < 5; i++)
                    blog.Posts.Add(new Post()
                    {
                        Content = "Some post content " + i,
                        Rating = (byte)i,
                        Title = "Some post Title " + i
                    });
                context.Blogs.Add(blog);
                context.SaveChanges();
            }

            using (var context = new BloggingContext(ConnectionStringEF))
            {
                var posts = from p in context.Posts
                            where p.Rating < 3
                            select p;
                Assert.AreEqual(3, posts.Count());
                foreach (var post in posts)
                {
                    Assert.Less(post.Rating, 3);
                }
            }
        }
开发者ID:Emill,项目名称:Npgsql,代码行数:32,代码来源:EntityFrameworkBasicTests.cs

示例15: CreateBloggingContext

        public void CreateBloggingContext()
        {
            using (var db = new BloggingContext(new NpgsqlConnection(ConnectionStringEF)))
            {
                if (!(db.Database.Connection is NpgsqlConnection))
                {
                    Assert.Fail(
                           "Connection type is \"" + db.Database.Connection.GetType().FullName + "\" should be \"" + typeof(NpgsqlConnection).FullName + "\"." + Environment.NewLine +
                           "Most likely wrong configuration in App.config file of Tests project.");
                }
                db.Database.Delete();
                var blog = new Blog { Name = "blogNameTest1" };
                db.Blogs.Add(blog);
                db.SaveChanges();

                var query = from b in db.Blogs
                            where b.Name == "blogNameTest1"
                            select b;
                Assert.AreEqual(1, query.Count());

                db.Database.Connection.Open();
                using (var command = db.Database.Connection.CreateCommand())
                {
                    command.CommandText = "select column_name, data_type, is_nullable, column_default from information_schema.columns where table_name = 'Blogs';";
                    List<string> expectedColumns = new List<string>(new string[] { "Name", "BlogId" });
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            Console.WriteLine((string)reader[0] + " " + (string)reader[1] + " " + (string)reader[2] + " " + (reader[3] ?? "").ToString());
                            switch ((string)reader[0])
                            {
                                case "Name":
                                    expectedColumns.Remove((string)reader[0]);
                                    Assert.AreEqual("text", (string)reader[1]);
                                    Assert.AreEqual("YES", (string)reader[2]);
                                    Assert.IsNullOrEmpty(reader[3] as string);
                                    break;
                                case "BlogId":
                                    expectedColumns.Remove((string)reader[0]);
                                    Assert.AreEqual("integer", (string)reader[1]);
                                    Assert.AreEqual("NO", (string)reader[2]);
                                    Assert.AreEqual("nextval('dbo.\"Blogs_BlogId_seq\"'::regclass)", reader[3] as string);
                                    break;
                                default:
                                    Assert.Fail("Unknown column '" + (string)reader[0] + "' in Blogs table.");
                                    break;
                            }
                        }
                    }
                    foreach (var columnName in expectedColumns)
                    {
                        Assert.Fail("Column '" + columnName + "' was not created in Blogs table.");
                    }
                }

                using (var command = db.Database.Connection.CreateCommand())
                {
                    command.CommandText = "select column_name, data_type, is_nullable, column_default from information_schema.columns where table_name = 'Posts';";
                    List<string> expectedColumns = new List<string>(new string[] { "PostId", "Title", "Content", "BlogId" });
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            Console.WriteLine((string)reader[0] + " " + (string)reader[1] + " " + (string)reader[2] + " " + (reader[3] ?? "").ToString());
                            switch ((string)reader[0])
                            {
                                case "PostId":
                                    expectedColumns.Remove((string)reader[0]);
                                    Assert.AreEqual("integer", (string)reader[1]);
                                    Assert.AreEqual("NO", (string)reader[2]);
                                    Assert.AreEqual("nextval('dbo.\"Posts_PostId_seq\"'::regclass)", (string)reader[3]);
                                    break;
                                case "Title":
                                    expectedColumns.Remove((string)reader[0]);
                                    Assert.AreEqual("text", (string)reader[1]);
                                    Assert.AreEqual("YES", (string)reader[2]);
                                    Assert.IsNullOrEmpty(reader[3] as string);
                                    break;
                                case "Content":
                                    expectedColumns.Remove((string)reader[0]);
                                    Assert.AreEqual("text", (string)reader[1]);
                                    Assert.AreEqual("YES", (string)reader[2]);
                                    Assert.IsNullOrEmpty(reader[3] as string);
                                    break;
                                case "BlogId":
                                    expectedColumns.Remove((string)reader[0]);
                                    Assert.AreEqual("integer", (string)reader[1]);
                                    Assert.AreEqual("NO", (string)reader[2]);
                                    Assert.AreEqual("0", (string)reader[3]);
                                    break;
                                case "UniqueId":
                                    expectedColumns.Remove((string)reader[0]);
                                    Assert.AreEqual("uuid", (string)reader[1]);
                                    Assert.AreEqual("NO", (string)reader[2]);
                                    Assert.AreEqual("'00000000-0000-0000-0000-000000000000'::uuid", reader[3] as string);
                                    //Assert.AreEqual("uuid_generate_v4()", reader[3] as string);
                                    break;
                                case "Rating":
                                    expectedColumns.Remove((string)reader[0]);
//.........这里部分代码省略.........
开发者ID:hultqvist,项目名称:Npgsql2,代码行数:101,代码来源:EntityFrameworkMigrationTests.cs


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