• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# BloggingContext类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: EnsureDeleted_will_delete_database_test

        private static async Task EnsureDeleted_will_delete_database_test(bool async)
        {
            using (var testDatabase = await SqlServerTestDatabase.Scratch(createDatabase: true))
            {
                testDatabase.Connection.Close();

                using (var context = new BloggingContext(testDatabase))
                {
                    Assert.True(async ? await context.Database.AsRelational().ExistsAsync() : context.Database.AsRelational().Exists());

                    if (async)
                    {
                        Assert.True(await context.Database.EnsureDeletedAsync());
                    }
                    else
                    {
                        Assert.True(context.Database.EnsureDeleted());
                    }

                    Assert.Equal(ConnectionState.Closed, context.Database.AsRelational().Connection.DbConnection.State);

                    Assert.False(async ? await context.Database.AsRelational().ExistsAsync() : context.Database.AsRelational().Exists());

                    Assert.Equal(ConnectionState.Closed, context.Database.AsRelational().Connection.DbConnection.State);
                }
            }
        }
开发者ID:Nyaoso,项目名称:EntityFramework,代码行数:27,代码来源:SqlServerDatabaseCreationTest.cs


示例2: DefaultModel

        protected DefaultModel(string blogusername = null)
        {
            _IUser = HttpContext.Current.User;

            //	The user that we're looking at.
            string viewUser;

            if (_IUser.Identity.IsAuthenticated)
            {
                viewUser = _IUser.Identity.Name;
            }
            else if (blogusername != null)
            {
                viewUser = blogusername;
            }
            else
            {
                viewUser = "tgobyrne";
            }

            using (var db = new BloggingContext())
            {
                User = (from u in db.Users
                        where u.Username == viewUser || u.FirstName == viewUser
                        select u).FirstOrDefault();

                Sections = (from p in User.Posts
                            select p.Section)
                            .Distinct()
                            .ToList();
            }

            HttpContext.Current.Items["User"] = User;
        }
开发者ID:TOByrne,项目名称:TGOByrne,代码行数:34,代码来源:DefaultModel.cs


示例3: TestGetAllowedEntityTypes

 public void TestGetAllowedEntityTypes()
 {
     var ctx = new BloggingContext("Blogging");
     var allowedTypes = DbContextExtensions.DbContextExtensions.GetAllowedEntityTypes<BloggingContext>(ctx);
     Assert.IsNotNull(allowedTypes);
     Assert.IsTrue(allowedTypes.Count > 0);
 }
开发者ID:scottyinthematrix,项目名称:DbContextExtensions,代码行数:7,代码来源:DbContextExtensionsTest.cs


示例4: 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


示例5: 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


示例6: Index

 // GET: Sql
 public ActionResult Index()
 {
     using (var context = new BloggingContext())
     {
         var blogs = context.Blogs.SqlQuery("SELECT * FROM dbo.Blogs").ToList();
     }
     return View();
 }
开发者ID:rnmisrahi,项目名称:JB,代码行数:9,代码来源:SqlController.cs


示例7: 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


示例8: Run

        public static void Run()
        {
            using (var context = new BloggingContext())
            {
                var blogs = context.Blogs
                    .FromSql("SELECT * FROM dbo.Blogs")
                    .ToList();
            }

            using (var context = new BloggingContext())
            {
                var blogs = context.Blogs
                    .FromSql("EXECUTE dbo.GetMostPopularBlogs")
                    .ToList();
            }

            using (var context = new BloggingContext())
            {
                var user = "johndoe";

                var blogs = context.Blogs
                    .FromSql("EXECUTE dbo.GetMostPopularBlogsForUser {0}", user)
                    .ToList();
            }

            using (var context = new BloggingContext())
            {
                var user = new SqlParameter("user", "johndoe");

                var blogs = context.Blogs
                    .FromSql("EXECUTE dbo.GetMostPopularBlogsForUser @user", user)
                    .ToList();
            }

            using (var context = new BloggingContext())
            {
                var searchTerm = ".NET";

                var blogs = context.Blogs
                    .FromSql("SELECT * FROM dbo.SearchBlogs {0}", searchTerm)
                    .Where(b => b.Rating > 3)
                    .OrderByDescending(b => b.Rating)
                    .ToList();
            }

            using (var context = new BloggingContext())
            {
                var searchTerm = ".NET";

                var blogs = context.Blogs
                    .FromSql("SELECT * FROM dbo.SearchBlogs {0}", searchTerm)
                    .Include(b => b.Posts)
                    .ToList();
            }
        }
开发者ID:CrazyHorse007,项目名称:EntityFramework.Docs,代码行数:55,代码来源:Sample.cs


示例9: Inserts_and_updates_are_batched_correctly

        public void Inserts_and_updates_are_batched_correctly()
        {
            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 {Name = "0"};
                var owner2 = new Owner {Name = "1" };
                context.Owners.Add(owner1);
                context.Owners.Add(owner2);

                var blog1 = new Blog
                {
                    Id = Guid.NewGuid(),
                    Owner = owner1,
                    Order = 1
                };

                context.Blogs.Add(blog1);
                expectedBlogs.Add(blog1);

                context.SaveChanges();

                owner2.Name = "2";

                blog1.Order = 0;
                var blog2 = new Blog
                {
                    Id = Guid.NewGuid(),
                    Owner = owner1,
                    Order = 1
                };

                context.Blogs.Add(blog2);
                expectedBlogs.Add(blog2);

                var blog3 = new Blog
                {
                    Id = Guid.NewGuid(),
                    Owner = owner2,
                    Order = 2
                };

                context.Blogs.Add(blog3);
                expectedBlogs.Add(blog3);

                context.SaveChanges();
            }

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


示例10: AdminCenterModel

 //public List<Tags> Tags { get; protected set; }
 //public List<Blog> Blogs { get; protected set; }
 //public List<Album> Albums { get; protected set; }
 //public List<Comment> Comments { get; protected set; }
 //public List<Picture> Pictures { get; protected set; }
 //public List<Post> Posts { get; protected set; }
 public AdminCenterModel(BloggingContext context = null)
     : base("tgobyrne")
 {
     if (context != null)
     {
         Context = context;
     }
     else
     {
         Context = new BloggingContext();
     }
 }
开发者ID:TOByrne,项目名称:TGOByrne,代码行数:18,代码来源:AdminCenterModel.cs


示例11: Exists_returns_true_when_database_exists_test

        private static async Task Exists_returns_true_when_database_exists_test(bool async)
        {
            using (var testDatabase = await SqlServerTestStore.CreateScratchAsync(createDatabase: true))
            {
                using (var context = new BloggingContext(testDatabase))
                {
                    Assert.True(async ? await context.Database.AsRelational().ExistsAsync() : context.Database.AsRelational().Exists());

                    Assert.Equal(ConnectionState.Closed, context.Database.AsRelational().Connection.DbConnection.State);
                }
            }
        }
开发者ID:thegido,项目名称:EntityFramework,代码行数:12,代码来源:SqlServerDatabaseCreationTest.cs


示例12: Exists_returns_false_when_database_doesnt_exist_test

        private static async Task Exists_returns_false_when_database_doesnt_exist_test(bool async)
        {
            using (var testDatabase = await SqlServerTestStore.CreateScratchAsync(createDatabase: false))
            {
                using (var context = new BloggingContext(testDatabase))
                {
                    var creator = context.GetService<IRelationalDatabaseCreator>();

                    Assert.False(async ? await creator.ExistsAsync() : creator.Exists());

                    Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);
                }
            }
        }
开发者ID:JamesWang007,项目名称:EntityFramework,代码行数:14,代码来源:SqlServerDatabaseCreationTest.cs


示例13: IsValid

        /// <summary>
        /// Checks if user with given password exists in the database
        /// </summary>
        /// <param name="_username">User name</param>
        /// <param name="_password">User password</param>
        /// <returns>True if user exist and password is correct</returns>
        public bool IsValid(string _username, string _password)
        {
            using (var db = new BloggingContext())
            {
                var username = _username;
                var password = Helpers.SHA1.Encode(_password);

                var user = (from u in db.Users
                            where u.Username == username && u.Password == password
                            select u).FirstOrDefault();

                return user != null;
            }
        }
开发者ID:TOByrne,项目名称:TGOByrne,代码行数:20,代码来源:User.cs


示例14: 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


示例15: 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


示例16: TestFixtureSetup

        public override void TestFixtureSetup()
        {
            base.TestFixtureSetup();
            using (var context = new BloggingContext(ConnectionStringEF))
            {
                if (context.Database.Exists())
                    context.Database.Delete();//We delete to be 100% schema is synced
                context.Database.Create();
            }

            // Create sequence for the IntComputedValue property.
            using (var createSequenceConn = new NpgsqlConnection(ConnectionStringEF))
            {
                createSequenceConn.Open();
                ExecuteNonQuery("create sequence blog_int_computed_value_seq", createSequenceConn);
                ExecuteNonQuery("alter table \"dbo\".\"Blogs\" alter column \"IntComputedValue\" set default nextval('blog_int_computed_value_seq');", createSequenceConn);

            }


        }
开发者ID:Emill,项目名称:Npgsql,代码行数:21,代码来源:EntityFrameworkBasicTests.cs


示例17: AddDefaultUser

        public static IResponse AddDefaultUser(BloggingContext db)
        {
            var user = new User
            {
                FirstName = "Tony",
                LastName = "O'Byrne",
                Email = "[email protected]",
                Username = "tgobyrne",
                Password = "",
                CreateDate = DateTime.Now,
                LastUpdateDate = DateTime.Now
            };

            user.Blog.Add(new Blog
            {
                Name = "Personal"
            });

            IResponse userResult = AddUser(db, user);
            return userResult;
        }
开发者ID:TOByrne,项目名称:TGOByrne,代码行数:21,代码来源:UserModel.cs


示例18: AdminController

        public AdminController()
        {
            //	Get all the User stuff
            using (var db = new BloggingContext())
            {
                var users = from user in db.Users
                            orderby user.LastName
                            select user;

                if (!users.Any())
                {
                    IResponse addUserRespose = UserModel.AddDefaultUser(db);
                    Messages = addUserRespose.messages;
                }

                Users = new List<User>();
                foreach (var user in users)
                {
                    Users.Add(user);
                }
            }
        }
开发者ID:TOByrne,项目名称:TGOByrne,代码行数:22,代码来源:AdminController.cs


示例19: TestFixtureSetup

        public override void TestFixtureSetup()
        {
            base.TestFixtureSetup();
            using (var context = new BloggingContext(ConnectionStringEF))
            {
                if (context.Database.Exists())
                    context.Database.Delete();//We delete to be 100% schema is synced
                context.Database.Create();
            }

            // Create sequence for the IntComputedValue property.
            using (var createSequenceConn = new NpgsqlConnection(ConnectionStringEF))
            {
                createSequenceConn.Open();
                ExecuteNonQuery("create sequence blog_int_computed_value_seq", createSequenceConn);
                ExecuteNonQuery("alter table \"dbo\".\"Blogs\" alter column \"IntComputedValue\" set default nextval('blog_int_computed_value_seq');", createSequenceConn);
                ExecuteNonQuery("alter table \"dbo\".\"Posts\" alter column \"VarbitColumn\" type varbit using null", createSequenceConn);
                ExecuteNonQuery("CREATE OR REPLACE FUNCTION \"dbo\".\"StoredAddFunction\"(integer, integer) RETURNS integer AS $$ SELECT $1 + $2; $$ LANGUAGE SQL;", createSequenceConn);
            }


        }
开发者ID:kraaden,项目名称:npgsql,代码行数:22,代码来源:EntityFrameworkBasicTests.cs


示例20: 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



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# BnfTerm类代码示例发布时间:2022-05-24
下一篇:
C# BlogRollItem类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap