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); } } }
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)); } }
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 = "******"; } 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; }
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; }
public void TestGetAllowedEntityTypes() { var ctx = new BloggingContext("Blogging"); var allowedTypes = DbContextExtensions.DbContextExtensions.GetAllowedEntityTypes<BloggingContext>(ctx); Assert.IsNotNull(allowedTypes); Assert.IsTrue(allowedTypes.Count > 0); }
// GET: Sql public ActionResult Index() { using (var context = new BloggingContext()) { var blogs = context.Blogs.SqlQuery("SELECT * FROM dbo.Blogs").ToList(); } return View(); }
protected override void SetUp() { base.SetUp(); using (var context = new BloggingContext(ConnectionStringEF)) { context.Blogs.RemoveRange(context.Blogs); context.Posts.RemoveRange(context.Posts); context.SaveChanges(); } }
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 = "******"; 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(); } }
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); }
//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(); } }
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); } } }
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); } } }
/// <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; } }
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 } } }
public static void Run() { using (var context = new BloggingContext()) { var blogs = context.Blogs.ToList(); } using (var context = new BloggingContext()) { var blog = context.Blogs .Single(b => b.BlogId == 1); } using (var context = new BloggingContext()) { var blogs = context.Blogs .Where(b => b.Url.Contains("dotnet")) .ToList(); } }
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); }
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); } }
public static void Run() { using (var context = new BloggingContext()) { var blogs = context.Blogs .OrderByDescending(blog => blog.Rating) .Select(blog => new { Id = blog.BlogId, Url = StandardizeUrl(blog.Url) }) .ToList(); } using (var context = new BloggingContext()) { var blogs = context.Blogs .Where(blog => StandardizeUrl(blog.Url).Contains("dotnet")) .ToList(); } }
public static IResponse AddDefaultUser(BloggingContext db) { var user = new User { FirstName = "Tony", LastName = "O'Byrne", Email = "*****@*****.**", Username = "******", Password = "", CreateDate = DateTime.Now, LastUpdateDate = DateTime.Now }; user.Blog.Add(new Blog { Name = "Personal" }); IResponse userResult = AddUser(db, user); return userResult; }
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); } } }
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); } }
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()); } }
public void GetUpdates() { using (var db = new BloggingContext()) { try { //var tags = (from t in db.Tags // select t) // .Distinct() // .ToList(); Updates = (from t in db.SiteUpdates where t.User.UserId == User.UserId select t) .OrderByDescending(p => p.Timestamp) .ToList(); } catch (Exception) { // There are either no tags, or no updates. } Posts = (from p in db.Posts where (from t in p.Tags select t.Tag.ToUpper()).Contains("UPDATE") == false && p.User.UserId == User.UserId select p) .OrderByDescending(p => p.Time) .ToList() //.Take(2) ; // Enumerate the tags; we'll need them. EnumerateTags(Updates); EnumerateTags(Posts); } }
public CalendarModel(BloggingContext db, DefaultModel pageModel) : base(pageModel) { if (db.Posts.Count() != 0) { LastPostDate = (from posts in db.Posts orderby posts.Time descending where (from t in posts.Tags select t.Tag.ToUpper()).Contains("UPDATE") == false && posts.Time != null select posts.Time.Value).First(); Now = LastPostDate; } else { Now = DateTime.Now; } FirstOfThisMonth = new DateTime(Now.Year, Now.Month, 1); DaysInThisMonth = DateTime.DaysInMonth(Now.Year, Now.Month); var FirstDayOfMonth = FirstOfThisMonth.DayOfWeek; GetDatesWithPostsThisMonth(db); Dictionary<int, DateInfo> firstRow = StartFirstRow(FirstDayOfMonth); CompleteFirstRow(firstRow); Dates = new List<Dictionary<int, DateInfo>>(); Dates.Add(firstRow); while (DateCounter <= DaysInThisMonth) { Dates.Add(FullRow()); } AddExtraNextMonthRow(Dates); }
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; } }
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); } } }
public JsonResult AddUser(User newUser) { using (var db = new BloggingContext()) { if (string.IsNullOrEmpty(newUser.Password)) { newUser.Password = ""; } newUser.CreateDate = DateTime.Now; newUser.LastUpdateDate = DateTime.Now; newUser.Blog.Add(new Blog { Name = "Personal" }); var userAdded = UserModel.AddUser(db, newUser); return new JsonResult { Data = userAdded }; } }
public PostService(BloggingContext context) { _context = context; }
public async Task Can_save_changes() { using (var testDatabase = await SqlServerTestStore.CreateScratchAsync()) { var loggingFactory = new TestSqlLoggerFactory(); var serviceProvider = new ServiceCollection() .AddEntityFrameworkSqlServer() .AddSingleton <ILoggerFactory>(loggingFactory) .BuildServiceProvider(); var optionsBuilder = new DbContextOptionsBuilder() .EnableSensitiveDataLogging() .UseSqlServer(testDatabase.ConnectionString) .UseInternalServiceProvider(serviceProvider); using (var db = new BloggingContext(optionsBuilder.Options)) { await CreateBlogDatabaseAsync <Blog>(db); } using (var db = new BloggingContext(optionsBuilder.Options)) { var toUpdate = db.Blogs.Single(b => b.Name == "Blog1"); toUpdate.Name = "Blog is Updated"; var updatedId = toUpdate.Id; var toDelete = db.Blogs.Single(b => b.Name == "Blog2"); toDelete.Name = "Blog to delete"; var deletedId = toDelete.Id; db.Entry(toUpdate).State = EntityState.Modified; db.Entry(toDelete).State = EntityState.Deleted; var toAdd = db.Add(new Blog { Name = "Blog to Insert", George = true, TheGu = new Guid("0456AEF1-B7FC-47AA-8102-975D6BA3A9BF"), NotFigTime = new DateTime(1973, 9, 3, 0, 10, 33, 777), ToEat = 64, OrNothing = 0.123456789, Fuse = 777, WayRound = 9876543210, Away = 0.12345f, AndChew = new byte[16] }).Entity; await db.SaveChangesAsync(); var addedId = toAdd.Id; Assert.NotEqual(0, addedId); Assert.Equal(EntityState.Unchanged, db.Entry(toUpdate).State); Assert.Equal(EntityState.Unchanged, db.Entry(toAdd).State); Assert.DoesNotContain(toDelete, db.ChangeTracker.Entries().Select(e => e.Entity)); Assert.Equal(3, TestSqlLoggerFactory.SqlStatements.Count); Assert.Contains("SELECT", TestSqlLoggerFactory.SqlStatements[0]); Assert.Contains("SELECT", TestSqlLoggerFactory.SqlStatements[1]); Assert.Contains("@p0: " + deletedId, TestSqlLoggerFactory.SqlStatements[2]); Assert.Contains("DELETE", TestSqlLoggerFactory.SqlStatements[2]); Assert.Contains("UPDATE", TestSqlLoggerFactory.SqlStatements[2]); Assert.Contains("INSERT", TestSqlLoggerFactory.SqlStatements[2]); var rows = await testDatabase.ExecuteScalarAsync <int>( $@"SELECT Count(*) FROM [dbo].[Blog] WHERE Id = {updatedId} AND Name = 'Blog is Updated'", CancellationToken.None); Assert.Equal(1, rows); rows = await testDatabase.ExecuteScalarAsync <int>( $@"SELECT Count(*) FROM [dbo].[Blog] WHERE Id = {deletedId}", CancellationToken.None); Assert.Equal(0, rows); rows = await testDatabase.ExecuteScalarAsync <int>( $@"SELECT Count(*) FROM [dbo].[Blog] WHERE Id = {addedId} AND Name = 'Blog to Insert'", CancellationToken.None); Assert.Equal(1, rows); } } }
public PostsController(IPostService postSvc, BloggingContext context) { _context = context; _postSvc = postSvc; }
public static void Seed() { var dbContext = new BloggingContext(); if (dbContext.Authors.Any()) { return; } var tags = new[] { new Tag { Id = "csharp", Description = "C#" }, new Tag { Id = "javascript", Description = "JavaScript" }, new Tag { Id = "cooking", Description = "Cooking" }, new Tag { Id = "egg", Description = "Egg" }, new Tag { Id = "forbeginners", Description = "For Beginners" }, new Tag { Id = "db", Description = "Databases" }, new Tag { Id = "ef", Description = "Entity Framework" }, new Tag { Id = "advanced", Description = "Advanced" }, new Tag { Id = "oriental", Description = "Oriental Cooking" } }; var blogs = new[] { new Blog { Created = DateTime.Now.AddDays(-100), Title = "Programmer's Spot" }, new Blog { Created = DateTime.Now.AddDays(-1000), Title = "Cooking at home" } }; var authors = new[] { new Author { Name = "Eduard", LastName = "Lepner", Posts = new List <Post> { new Post { Title = "How to start with EF and don't shoot your head", Content = "Some interesting post content", Blog = blogs[0], Rating = 5, Created = DateTime.Now.AddDays(-1) }, new Post { Title = "Functional Programming For Body Builders", Content = "Some content", Rating = 4, Blog = blogs[0], Created = DateTime.Today }, new Post { Title = "How to cook an Egg", Content = "Put an egg into tea pot and turn it on.", Blog = blogs[1], Created = DateTime.Now } } }, new Author { Name = "John", LastName = "Doe", Posts = new List <Post> { new Post { Title = "John First Post Title", Content = "Some content for John's first post.", Blog = blogs[0] }, new Post { Title = "John Second Post Title", Content = "Some content for John's second post.", Blog = blogs[1] } } }, new Author { Name = "Jan", LastName = "Kovalski", Posts = new List <Post> { new Post { Title = "Jan's first post", Content = "Some content for Jan's first post.", Blog = blogs[1], Rating = 3 } } } }; var posts = authors.SelectMany(x => x.Posts).ToArray(); posts[0].AssignTags("csharp", "db", "ef"); posts[1].AssignTags("csharp", "forbeginners"); posts[2].AssignTags("forbeginners"); posts[3].AssignTags("javascript", "db", "advanced", "csharp"); posts[4].AssignTags("oriental", "db", "advanced", "csharp"); dbContext.Blogs.AddRange(blogs); dbContext.Authors.AddRange(authors); dbContext.Tags.AddRange(tags); dbContext.SaveChanges(); }
public ArticlesController(BloggingContext context) { _db = context; }
public UnitTestBase(ITestOutputHelper output) { Effort.Provider.EffortProviderConfiguration.RegisterProvider(); this._context = PrepareContext(); DTORepositoryContainer.InitializeDtoMapper <BloggingContext>(); }
public async System.Threading.Tasks.Task Stream_Generate_Insert_For_Multiple_Entities() { using (var testDatabase = SqlServerTestStore.Create(DatabaseName)) { var loggingFactory = new TestSqlLoggerFactory(); var serviceProvider = new ServiceCollection() .AddEntityFrameworkSqlServer() .AddSingleton <ILoggerFactory>(loggingFactory) .BuildServiceProvider(); var optionsBuilder = new DbContextOptionsBuilder() .EnableSensitiveDataLogging() .UseSqlServer(testDatabase.ConnectionString, b => b.ApplyConfiguration()) .UseInternalServiceProvider(serviceProvider); using (var db = new BloggingContext(optionsBuilder.Options)) { await CreateBlogDatabaseAsync <Blog>(db); } loggingFactory.Clear(); using (var db = new BloggingContext(optionsBuilder.Options)) { var toAdd = db.Add(new Blog { Name = "Blog to Insert", George = true, TheGu = new Guid("0456AEF1-B7FC-47AA-8102-975D6BA3A9BF"), NotFigTime = new DateTime(1973, 9, 3, 0, 10, 33, 777), ToEat = 64, OrNothing = 0.123456789, Fuse = 777, WayRound = 9876543210, Away = 0.12345f, AndChew = new byte[16] }).Entity; var recordTwo = db.Add(new Blog { Name = "Another Blog to Insert", George = true, TheGu = new Guid("0456AEF1-B7FC-47AA-8102-975D6BA3A9BE"), NotFigTime = new DateTime(1974, 9, 3, 0, 10, 33, 777), ToEat = 65, OrNothing = 0.123456789, Fuse = 777, WayRound = 9876543210, Away = 0.12345f, AndChew = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } }).Entity; var statement = ""; using (var stream = new MemoryStream()) { db.Generate(stream); stream.Seek(0, SeekOrigin.Begin); var streamReader = new StreamReader(stream); statement = await streamReader.ReadToEndAsync(); Assert.IsTrue(!string.IsNullOrEmpty(statement)); } var reader = new StringReader(statement); IList <ParseError> errors; var parser = new TSql140Parser(false); var parseResult = parser.Parse(reader, out errors); Assert.IsFalse(errors.Any()); } } }
public void PerformanceTest() { MemoryCacheProvider.ClearCache(); decimal loopCount = 1000; var loggerProvider = new DebugLoggerProvider(); var loggerFactory = new LoggerFactory(new[] { loggerProvider }); var options = new DbContextOptionsBuilder <BloggingContext>() .UseLoggerFactory(loggerFactory) .UseInMemoryDatabase(databaseName: "PerformanceTest") .Options; // create test entries using (var initContext = new BloggingContext(options)) { initContext.ChangeTracker.AutoDetectChangesEnabled = false; for (int i = 0; i < 100000; i++) { initContext.Blogs.Add(new Blog { Url = $"http://sample.com/cat{i}", Posts = new List <Post> { { new Post { Title = $"Post{1}" } } } }); } initContext.SaveChanges(); } var rawOptions = new DbContextOptionsBuilder <BloggingContext>() .UseLoggerFactory(loggerFactory) .UseInMemoryDatabase(databaseName: "PerformanceTest") .Options; using (var performanceContext = new BloggingContext(rawOptions)) { Stopwatch watch = new Stopwatch(); watch.Start(); // raw queries for (int i = 0; i < loopCount; i++) { var result = performanceContext.Blogs .Where(d => d.BlogId >= 0) .Take(100) .ToList(); } var rawTimeSpan = watch.Elapsed; Debug.WriteLine($"Average default context database query duration [+{TimeSpan.FromTicks((long)(rawTimeSpan.Ticks / loopCount))}]."); } using (var performanceContext = new BloggingContext(options)) { Stopwatch watch = new Stopwatch(); watch.Start(); // uncached queries for (int i = 0; i < loopCount; i++) { var result = performanceContext.Blogs .Where(d => d.BlogId >= 0) .Take(100) .ToList(); } var uncachedTimeSpan = watch.Elapsed; // caching query result performanceContext.Blogs .Where(d => d.BlogId >= 0) .Cacheable(TimeSpan.FromMinutes(10)) .Take(100) .ToList(); watch.Restart(); // cached queries for (int i = 0; i < loopCount; i++) { var result = performanceContext.Blogs .Where(d => d.BlogId >= 0) .Cacheable(TimeSpan.FromMinutes(10)) .Take(100) .ToList(); } var cachedTimeSpan = watch.Elapsed; // find log entries var queryResultsCachedCount = loggerProvider.Entries.Where(e => e.EventId == CacheableEventId.QueryResultCached).Count(); var cacheHitsCount = loggerProvider.Entries.Where(e => e.EventId == CacheableEventId.CacheHit).Count(); // check cache event counts Assert.IsTrue(queryResultsCachedCount == 1); Assert.IsTrue(cacheHitsCount == loopCount); Debug.WriteLine($"Average database query duration [+{TimeSpan.FromTicks((long)(uncachedTimeSpan.Ticks / loopCount))}]."); Debug.WriteLine($"Average cache query duration [+{TimeSpan.FromTicks((long)(cachedTimeSpan.Ticks / loopCount))}]."); Debug.WriteLine($"Cached queries are x{((Decimal)uncachedTimeSpan.Ticks / (Decimal)cachedTimeSpan.Ticks)-1:N2} times faster."); Assert.IsTrue(cachedTimeSpan < uncachedTimeSpan); } }
public async Task Paging_lots_of_elements(int itemsCount) { try { // Run the test against one instance of the context using (var context = new BloggingContext(Setup.DbOpts)) { var repository = new AspNetCore.ExistingDb.Repositories.HashesRepository(context, Setup.Conf, Setup.Cache, Setup.Logger, Setup.ServerTiming); var tasks = new List <Task>(itemsCount + 1); for (int i = 0; i < itemsCount; i++) { tasks.Add(repository.AddRangeAsync(new[] { new ThinHashes { Key = $"alamakota_{i}", HashMD5 = $"dc246bcdd6cb3548579770a034d2e678_{i}", HashSHA256 = $"63b347973bb99fed9277b33cb4646b205e9a31331acfa574add3d2351f445e43_{i}" }, new ThinHashes { Key = $"fakefakef_{i}", HashMD5 = $"fakefakefakefakefakefakefakefake_{i}", HashSHA256 = $"fakefakefakefakefakefakefakefakefakefakefakefakefakefakefakefake_{i}" } })); } Task.WaitAll(tasks.ToArray()); await repository.SaveAsync(); } using (var context = new BloggingContext(Setup.DbOpts)) { var repository = new AspNetCore.ExistingDb.Repositories.HashesRepository(context, Setup.Conf, Setup.Cache, Setup.Logger, Setup.ServerTiming); var found = await repository.PagedSearchAsync("Key", "asc", "fake", 2, 10, CancellationToken); Assert.True(found.Count > 0); Assert.NotEmpty(found.Itemz); Assert.Equal(found.Count, itemsCount); Assert.Equal(10, found.Itemz.Count()); Assert.Equal("fakefakef_10", found.Itemz.First()[0]); Assert.Equal("fakefakefakefakefakefakefakefakefakefakefakefakefakefakefakefake_10", found.Itemz.First()[2]); } } catch (Exception) { throw; } finally { Setup.Conn.Dispose(); } //2nd run var db = SetupInMemoryDB(); db.Wait(); Setup = db.Result; try { // Run the test against one instance of the context using (var context = new BloggingContext(Setup.DbOpts)) { var repository = new AspNetCore.ExistingDb.Repositories.HashesRepository(context, Setup.Conf, Setup.Cache, Setup.Logger, Setup.ServerTiming); var tasks = new List <Task>(itemsCount + 1); for (int i = 0; i < itemsCount; i++) { tasks.Add(repository.AddRangeAsync(new[] { new ThinHashes { Key = $"alamakota_{i}", HashMD5 = $"dc246bcdd6cb3548579770a034d2e678_{i}", HashSHA256 = $"63b347973bb99fed9277b33cb4646b205e9a31331acfa574add3d2351f445e43_{i}" }, new ThinHashes { Key = $"fakefakef_{i}", HashMD5 = $"fakefakefakefakefakefakefakefake_{i}", HashSHA256 = $"fakefakefakefakefakefakefakefakefakefakefakefakefakefakefakefake_{i}" } })); } Task.WaitAll(tasks.ToArray()); await repository.SaveAsync(); } using (var context = new BloggingContext(Setup.DbOpts)) { var repository = new AspNetCore.ExistingDb.Repositories.HashesRepository(context, Setup.Conf, Setup.Cache, Setup.Logger, Setup.ServerTiming); var found = await repository.PagedSearchAsync("Key", "asc", "63b347973bb99f", 2, 10, CancellationToken); Assert.True(found.Count > 0); Assert.NotEmpty(found.Itemz); Assert.Equal(found.Count, itemsCount); Assert.Equal(10, found.Itemz.Count()); Assert.Equal("alamakota_10", found.Itemz.First()[0]); Assert.Equal("63b347973bb99fed9277b33cb4646b205e9a31331acfa574add3d2351f445e43_10", found.Itemz.First()[2]); } } catch (Exception) { throw; } }
public PostsController(BloggingContext context) { _context = context; }
public BlogService(BloggingContext context) { _context = context; }
public async Task CalculateHashesInfo() { try { // Run the test against one instance of the context using (var context = new BloggingContext(Setup.DbOpts)) { var repository = new AspNetCore.ExistingDb.Repositories.HashesRepository(context, Setup.Conf, Setup.Cache, Setup.Logger, Setup.ServerTiming); int count = 100; var tasks = new List <Task>(count + 1); for (int i = 0; i < count; i++) { tasks.Add(repository.AddRangeAsync(new[] { new ThinHashes { Key = $"alamakota_{i}", HashMD5 = $"dc246bcdd6cb3548579770a034d2e678_{i}", HashSHA256 = $"63b347973bb99fed9277b33cb4646b205e9a31331acfa574add3d2351f445e43_{i}" }, new ThinHashes { Key = $"bakebakeb_{i}", HashMD5 = $"bakebakebakebakebakebakebakebake_{i}", HashSHA256 = $"bakebakebakebakebakebakebakebakebakebakebakebakebakebakebakebake_{i}" }, new ThinHashes { Key = $"cakecakec_{i}", HashMD5 = $"cakecakecakecakecakecakecakecake_{i}", HashSHA256 = $"cakecakecakecakecakecakecakecakecakecakecakecakecakecakecakecake_{i}" }, })); } Task.WaitAll(tasks.ToArray()); await repository.SaveAsync(); } using (var context = new BloggingContext(Setup.DbOpts)) { var repository = new AspNetCore.ExistingDb.Repositories.HashesRepository(context, Setup.Conf, Setup.Cache, Setup.Logger, Setup.ServerTiming); var factory = new LoggerFactory(); var logger = factory.CreateLogger <HashesRepository>(); var expected = await repository.CurrentHashesInfo; Assert.Null(expected); var res0 = await repository.CalculateHashesInfo(logger, Setup.DbOpts); Assert.NotNull(res0); var res1 = await repository.CalculateHashesInfo(logger, Setup.DbOpts); Assert.NotNull(res1); Assert.Same(res0, res1); Assert.Equal("abc", res0.Alphabet); Assert.Equal(300, res0.Count); Assert.False(res0.IsCalculating); Assert.Equal(12, res0.KeyLength); expected = await repository.CurrentHashesInfo; Assert.NotNull(expected); Assert.Equal(res1.ID, expected.ID); Assert.Equal(res1.Alphabet, expected.Alphabet); Assert.Equal(res1.Count, expected.Count); Assert.Equal(res1.IsCalculating, expected.IsCalculating); Assert.Equal(res1.KeyLength, expected.KeyLength); Assert.Equal(res1.ToString(), expected.ToString()); } } catch (Exception) { throw; } }
public static TestDatabaseCreator GetDatabaseCreator(BloggingContext context) => (TestDatabaseCreator)context.GetService <IRelationalDatabaseCreator>();
public CommentCollectionsController(BloggingContext context) { _context = context; }
/// <summary> /// Testing cache expiration functionality. /// </summary> //[TestMethod] public void ExpirationTest() { MemoryCacheProvider.ClearCache(); var loggerProvider = new DebugLoggerProvider(); var loggerFactory = new LoggerFactory(new[] { loggerProvider }); var options = new DbContextOptionsBuilder <BloggingContext>() .UseLoggerFactory(loggerFactory) .UseInMemoryDatabase(databaseName: "ExpirationTest") .Options; // create test entries using (var initContext = new BloggingContext(options)) { initContext.Blogs.Add(new Blog { BlogId = 1, Url = "http://sample.com/cats" }); initContext.Blogs.Add(new Blog { BlogId = 2, Url = "http://sample.com/catfish" }); initContext.Blogs.Add(new Blog { BlogId = 3, Url = "http://sample.com/dogs" }); initContext.SaveChanges(); } using (var expirationContext = new BloggingContext(options)) { // shoud not hit cache, because first execution var result = expirationContext.Blogs .Where(d => d.BlogId == 1) .Cacheable(TimeSpan.FromSeconds(5)) .ToList(); // shoud hit cache, because second execution result = expirationContext.Blogs .Where(d => d.BlogId == 1) .Cacheable(TimeSpan.FromSeconds(5)) .ToList(); // shoud not hit cache, because different parameter result = expirationContext.Blogs .Where(d => d.BlogId == 2) .Cacheable(TimeSpan.FromSeconds(5)) .ToList(); Thread.Sleep(TimeSpan.FromSeconds(10)); // shoud not hit cache, because expiration result = expirationContext.Blogs .Where(d => d.BlogId == 1) .Cacheable(TimeSpan.FromSeconds(5)) .ToList(); } // find "cache hit" log entries var logs = loggerProvider.Entries.Where(e => e.EventId == CacheableEventId.CacheHit); // cache should hit one time Assert.IsTrue(logs.Count() == 1); }
public void TestCacheReaderRaw() { var test = GetTestEntity(); using (var ctx = new BloggingContext(ConnectionString)) { ctx.Tests.Add(test); ctx.SaveChanges(); test = ctx.Tests.Single(); } using (var ctx = new BloggingContext(ConnectionString)) { var cmd = GetEntityCommand(ctx, "SELECT VALUE Test FROM BloggingContext.Tests AS Test"); using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)) { // Check schema. Assert.Throws <NotSupportedException>(() => reader.GetSchemaTable()); Assert.AreEqual(0, reader.Depth); Assert.AreEqual(-1, reader.RecordsAffected); Assert.IsTrue(reader.HasRows); Assert.IsFalse(reader.IsClosed); Assert.AreEqual(11, reader.FieldCount); Assert.AreEqual(11, reader.VisibleFieldCount); // Check field names. Assert.AreEqual("Edm.Int32", reader.GetDataTypeName(0)); Assert.AreEqual("Edm.Byte", reader.GetDataTypeName(1)); Assert.AreEqual("Edm.Int16", reader.GetDataTypeName(2)); Assert.AreEqual("Edm.Int64", reader.GetDataTypeName(3)); Assert.AreEqual("Edm.Single", reader.GetDataTypeName(4)); Assert.AreEqual("Edm.Double", reader.GetDataTypeName(5)); Assert.AreEqual("Edm.Decimal", reader.GetDataTypeName(6)); Assert.AreEqual("Edm.Boolean", reader.GetDataTypeName(7)); Assert.AreEqual("Edm.String", reader.GetDataTypeName(8)); Assert.AreEqual("Edm.Guid", reader.GetDataTypeName(9)); Assert.AreEqual("Edm.DateTime", reader.GetDataTypeName(10)); // Check field types. Assert.AreEqual(typeof(int), reader.GetFieldType(0)); Assert.AreEqual(typeof(byte), reader.GetFieldType(1)); Assert.AreEqual(typeof(short), reader.GetFieldType(2)); Assert.AreEqual(typeof(long), reader.GetFieldType(3)); Assert.AreEqual(typeof(float), reader.GetFieldType(4)); Assert.AreEqual(typeof(double), reader.GetFieldType(5)); Assert.AreEqual(typeof(decimal), reader.GetFieldType(6)); Assert.AreEqual(typeof(bool), reader.GetFieldType(7)); Assert.AreEqual(typeof(string), reader.GetFieldType(8)); Assert.AreEqual(typeof(Guid), reader.GetFieldType(9)); Assert.AreEqual(typeof(DateTime), reader.GetFieldType(10)); // Read. Assert.IsTrue(reader.Read()); // Test values array. var vals = new object[reader.FieldCount]; reader.GetValues(vals); Assert.AreEqual(test.Byte, vals[reader.GetOrdinal("Byte")]); Assert.AreEqual(test.Short, vals[reader.GetOrdinal("Short")]); Assert.AreEqual(test.ArrayReaderTestId, vals[reader.GetOrdinal("ArrayReaderTestId")]); Assert.AreEqual(test.Long, vals[reader.GetOrdinal("Long")]); Assert.AreEqual(test.Float, vals[reader.GetOrdinal("Float")]); Assert.AreEqual(test.Double, vals[reader.GetOrdinal("Double")]); Assert.AreEqual(test.Decimal, vals[reader.GetOrdinal("Decimal")]); Assert.AreEqual(test.Bool, vals[reader.GetOrdinal("Bool")]); Assert.AreEqual(test.String, vals[reader.GetOrdinal("String")]); Assert.AreEqual(test.Guid, vals[reader.GetOrdinal("Guid")]); Assert.AreEqual(test.DateTime, vals[reader.GetOrdinal("DateTime")]); } using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)) { // Read. Assert.IsTrue(reader.Read()); // Test separate values. Assert.AreEqual(test.ArrayReaderTestId, reader.GetInt32(0)); Assert.AreEqual(test.Byte, reader.GetByte(1)); Assert.AreEqual(test.Short, reader.GetInt16(2)); Assert.AreEqual(test.Long, reader.GetInt64(3)); Assert.AreEqual(test.Float, reader.GetFloat(4)); Assert.AreEqual(test.Double, reader.GetDouble(5)); Assert.AreEqual(test.Decimal, reader.GetDecimal(6)); Assert.AreEqual(test.Bool, reader.GetBoolean(7)); Assert.AreEqual(test.String, reader.GetString(8)); Assert.AreEqual(test.Guid, reader.GetGuid(9)); Assert.AreEqual(test.DateTime, reader.GetDateTime(10)); } } }
public BlogManager(BloggingContext ctx) { this.ctx = ctx; }
public async System.Threading.Tasks.Task Stream_Generate_For_DML() { using (var testDatabase = SqlServerTestStore.Create(DatabaseName)) { var loggingFactory = new TestSqlLoggerFactory(); var serviceProvider = new ServiceCollection() .AddEntityFrameworkSqlServer() .AddSingleton <ILoggerFactory>(loggingFactory) .BuildServiceProvider(); var optionsBuilder = new DbContextOptionsBuilder() .EnableSensitiveDataLogging() .UseSqlServer(testDatabase.ConnectionString, b => b.ApplyConfiguration()) .UseInternalServiceProvider(serviceProvider); using (var db = new BloggingContext(optionsBuilder.Options)) { await CreateBlogDatabaseAsync <Blog>(db); } loggingFactory.Clear(); using (var db = new BloggingContext(optionsBuilder.Options)) { var toUpdate = db.Blogs.Single(b => b.Name == "Blog1"); toUpdate.Name = "Blog is Updated"; var updatedId = toUpdate.Id; var toDelete = db.Blogs.Single(b => b.Name == "Blog2"); toDelete.Name = "Blog to delete"; var deletedId = toDelete.Id; db.Entry(toUpdate).State = EntityState.Modified; db.Entry(toDelete).State = EntityState.Deleted; var toAdd = db.Add(new Blog { Name = "Blog to Insert", George = true, TheGu = new Guid("0456AEF1-B7FC-47AA-8102-975D6BA3A9BF"), NotFigTime = new DateTime(1973, 9, 3, 0, 10, 33, 777), ToEat = 64, OrNothing = 0.123456789, Fuse = 777, WayRound = 9876543210, Away = 0.12345f, AndChew = new byte[16] }).Entity; var statement = ""; using (var stream = new MemoryStream()) { db.Generate(stream); stream.Seek(0, SeekOrigin.Begin); var streamReader = new StreamReader(stream); statement = await streamReader.ReadToEndAsync(); Assert.IsTrue(!string.IsNullOrEmpty(statement)); } var reader = new StringReader(statement); IList <ParseError> errors; var parser = new TSql140Parser(false); var parseResult = parser.Parse(reader, out errors); Assert.IsFalse(errors.Any()); //var expectedStatement = "EXECUTE sp_executesql N'INSERT INTO Blog ([AndChew], [Away], [Fuse], [George], [Name], [NotFigTime], [OrNothing], [TheGu], [ToEat], [WayRound]) VALUES (@p0,@p1,@p2,@p3,@p4,@p5,@p6,@p7,@p8,@p9)', N'@p0 varbinary(max),@p1 real,@p2 smallint,@p3 bit,@p4 nvarchar(max),@p5 datetime2,@p6 float,@p7 uniqueidentifier,@p8 tinyint,@p9 bigint', @p0 = 0x00000000000000000000000000000000,@p1 = 0.12345,@p2 = 777,@p3 = True,@p4 = 'Blog to Insert',@p5 = '9/3/1973 12:10:33 AM',@p6 = 0.123456789,@p7 = '0456aef1-b7fc-47aa-8102-975d6ba3a9bf',@p8 = 64,@p9 = 9876543210"; //Assert.AreEqual(expectedStatement, statement); } } }
public void TestComplicatedQueriesWithApply() { if ((BackendVersion.Major > 9) || (BackendVersion.Major == 9 && BackendVersion.Minor >= 3)) { using (var context = new BloggingContext(ConnectionStringEF)) { context.Database.Log = Console.Out.WriteLine; // Test Apply (from t1 in context.Blogs from t2 in context.Posts.Where(p => p.BlogId == t1.BlogId).Take(1) select new { t1, t2 }).ToArray(); Action<string> elinq = (string query) => { new System.Data.Entity.Core.Objects.ObjectQuery<System.Data.Common.DbDataRecord>(query, ((System.Data.Entity.Infrastructure.IObjectContextAdapter)context).ObjectContext).ToArray(); }; // Joins, apply elinq("Select value Blogs.BlogId From Blogs outer apply (Select p1.BlogId as bid, p1.PostId as bid2 from Posts as p1 left outer join (Select value p.PostId from Posts as p where p.PostId < Blogs.BlogId)) as b outer apply (Select p.PostId from Posts as p where p.PostId < b.bid)"); // Just some really crazy query that results in an apply as well context.Blogs.Select(b => new { b, b.BlogId, n = b.Posts.Select(p => new { t = p.Title + b.Name, n = p.Blog.Posts.Count(p2 => p2.BlogId < 4) }).Take(2) }).ToArray(); } } }
public CustomBlogRepository(BloggingContext dbContext) : base(dbContext) { }
private async Task RoundTripChanges <TBlog>() where TBlog : class, IBlog, new() { using (var testDatabase = await SqlServerTestStore.CreateScratchAsync()) { var optionsBuilder = new DbContextOptionsBuilder() .UseSqlServer(testDatabase.ConnectionString) .UseInternalServiceProvider(_fixture.ServiceProvider); int blog1Id; int blog2Id; int blog3Id; using (var context = new BloggingContext <TBlog>(optionsBuilder.Options)) { var blogs = await CreateBlogDatabaseAsync <TBlog>(context); blog1Id = blogs[0].Id; blog2Id = blogs[1].Id; Assert.NotEqual(0, blog1Id); Assert.NotEqual(0, blog2Id); Assert.NotEqual(blog1Id, blog2Id); } using (var context = new BloggingContext <TBlog>(optionsBuilder.Options)) { var blogs = context.Blogs.ToList(); Assert.Equal(2, blogs.Count); var blog1 = blogs.Single(b => b.Name == "Blog1"); Assert.Equal(blog1Id, blog1.Id); Assert.Equal("Blog1", blog1.Name); Assert.True(blog1.George); Assert.Equal(new Guid("0456AEF1-B7FC-47AA-8102-975D6BA3A9BF"), blog1.TheGu); Assert.Equal(new DateTime(1973, 9, 3, 0, 10, 33, 777), blog1.NotFigTime); Assert.Equal(64, blog1.ToEat); Assert.Equal(0.123456789, blog1.OrNothing); Assert.Equal(777, blog1.Fuse); Assert.Equal(9876543210, blog1.WayRound); Assert.Equal(0.12345f, blog1.Away); Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, blog1.AndChew); blog1.Name = "New Name"; var blog2 = blogs.Single(b => b.Name == "Blog2"); Assert.Equal(blog2Id, blog2.Id); blog2.Name = null; blog2.NotFigTime = new DateTime(); blog2.AndChew = null; var blog3 = context.Add(new TBlog()).Entity; await context.SaveChangesAsync(); blog3Id = blog3.Id; Assert.NotEqual(0, blog3Id); } using (var context = new BloggingContext <TBlog>(optionsBuilder.Options)) { var blogs = context.Blogs.ToList(); Assert.Equal(3, blogs.Count); Assert.Equal("New Name", blogs.Single(b => b.Id == blog1Id).Name); var blog2 = blogs.Single(b => b.Id == blog2Id); Assert.Null(blog2.Name); Assert.Equal(blog2.NotFigTime, new DateTime()); Assert.Null(blog2.AndChew); var blog3 = blogs.Single(b => b.Id == blog3Id); Assert.Null(blog3.Name); Assert.Equal(blog3.NotFigTime, new DateTime()); Assert.Null(blog3.AndChew); } } }
public IndexModel(BloggingContext db) { _db = db; }
public APIController(BloggingContext context) { _context = context; }
public void SingleProjectionExpressionTest() { MemoryCacheProvider.ClearCache(); var loggerProvider = new DebugLoggerProvider(); var loggerFactory = new LoggerFactory(new[] { loggerProvider }); var options = new DbContextOptionsBuilder <BloggingContext>() .UseLoggerFactory(loggerFactory) .UseInMemoryDatabase(databaseName: "ProjectionExpressionTest") .Options; // create test entries using (var initContext = new BloggingContext(options)) { initContext.Blogs.Add(new Blog { BlogId = 1, Url = "http://sample.com/cats" }); initContext.Blogs.Add(new Blog { BlogId = 2, Url = "http://sample.com/catfish" }); initContext.Blogs.Add(new Blog { BlogId = 3, Url = "http://sample.com/dogs" }); initContext.SaveChanges(); } using (var projectionContext = new BloggingContext(options)) { // shoud not hit cache, because first execution var result = projectionContext.Blogs .Where(d => d.BlogId == 1) .Select(d => new { d.BlogId, d.Rating }) .Cacheable(TimeSpan.FromMinutes(5)) .SingleOrDefault(); Thread.Sleep(TimeSpan.FromSeconds(1)); // shoud hit cache, because second execution var cachedResult = projectionContext.Blogs .Where(d => d.BlogId == 1) .Select(d => new { d.BlogId, d.Rating }) .Cacheable(TimeSpan.FromMinutes(5)) .SingleOrDefault(); Assert.IsNotNull(result); Assert.AreSame(result, cachedResult); } // find "cache hit" log entries var logs = loggerProvider.Entries.Where(e => e.EventId == CacheableEventId.CacheHit); // cache should hit one time Assert.IsTrue(logs.Count() == 1); }
public UserRepository(BloggingContext databaseContext) { _databaseContext = databaseContext; }
public static void Seed(this BloggingContext context) { context .Blogs .AddRange( new Blog { Url = "http://blog1.com", Rating = 5, Posts = { new Post() { Content = "Post 1 content", Title = "Post 1" }, new Post() { Content = "Post 2 content", Title = "Post 2" }, new Post() { Content = "Post 3 content", Title = "Post 3" } } }, new Blog { Url = "http://blog2.com", Rating = 7, Posts = { new Post() { Content = "Post 4 content", Title = "Post 4" }, new Post() { Content = "Post 5 content", Title = "Post 5" }, new Post() { Content = "Post 6 content", Title = "Post 6" } } }, new Blog { Url = "http://blog3.com", Rating = 4, Posts = { new Post() { Content = "Post 7 content", Title = "Post 7" }, new Post() { Content = "Post 8 content", Title = "Post 8" }, new Post() { Content = "Post 9 content", Title = "Post 9" } } } ); context.SaveChanges(); }
public CommentsController(BloggingContext bloggingContext) { _bloggingContext = bloggingContext; }
public void InsertAndSelect() { 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.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(1, context.NoColumnsEntities.Count()); } }
public BloggingController(BloggingContext bloggingContext) { _bloggingContext = bloggingContext; }
public CitiesController(BloggingContext context) { _context = context; }
public WeatherForecastController(ILogger <WeatherForecastController> logger, BloggingContext dbContext) { _logger = logger; _dbContext = dbContext; }
public JsonResult RemoveUser(string username, string userid) { using (var db = new BloggingContext()) { var user = (from u in db.Users where u.Username.ToLower() == username.ToLower() select u).First(); // Sanity check to make sure that the inputs haven't been // fiddled with... var hashCheck = new Hash(username, user.UserId, user.Email).GetHash(); if (userid != hashCheck) { return new JsonResult { Data = new { success = false, message = "It looks like the request has been tampered with." } }; } var blogModel = new Blogs.IndexModel(); if (blogModel.BlogExists(user.Username)) { blogModel.RemoveBlog(db, user.Username); } var userRemoved = UserModel.RemoveUser(db, user); return new JsonResult { Data = userRemoved }; } }
public BlogRepository(BloggingContext context) { _context = context; }