public async Task <IActionResult> Create(Blog blog)
        {
            if (!ModelState.IsValid)
            {
                return(View(blog));
            }
            if (blog.Photo != null)
            {
                string type = Path.GetExtension(blog.Photo.FileName);
                string name = $"{DateTime.Now.ToString("ssmmhhddMMyyyy")}{type}";
                // путь к папке Files
                string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/photos", name);

                // сохраняем файл в папку Files в каталоге wwwroot
                using (var fileStream = new FileStream(path, FileMode.Create))
                {
                    await blog.Photo.CopyToAsync(fileStream);
                }

                blog.PhotoUrl = "/photos/" + name;
            }
            blog.Author = User.Identity.Name;

            db.Blogs.Add(blog);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Beispiel #2
0
        public static void Working_with_default_values_4()
        {
            Console.WriteLine($">>>> Sample: {nameof(Working_with_default_values_4)}");
            Console.WriteLine();

            Helpers.RecreateCleanDatabase();

            #region Working_with_default_values_4
            using var context = new BlogsContext();

            var fooA = new Foo3 {
                Count = 10
            };
            var fooB = new Foo3 {
                Count = 0
            };
            var fooC = new Foo3();

            context.AddRange(fooA, fooB, fooC);
            context.SaveChanges();

            Debug.Assert(fooA.Count == 10);
            Debug.Assert(fooB.Count == 0);
            Debug.Assert(fooC.Count == -1);
            #endregion

            Console.WriteLine();
        }
Beispiel #3
0
        public static void Working_with_default_values_1()
        {
            Console.WriteLine($">>>> Sample: {nameof(Working_with_default_values_1)}");
            Console.WriteLine();

            Helpers.RecreateCleanDatabase();

            #region Working_with_default_values_1
            using var context = new BlogsContext();

            context.AddRange(
                new Token {
                Name = "A"
            },
                new Token {
                Name = "B", ValidFrom = new DateTime(1111, 11, 11, 11, 11, 11)
            });

            context.SaveChanges();

            Console.WriteLine(context.ChangeTracker.DebugView.LongView);
            #endregion

            Console.WriteLine();
        }
Beispiel #4
0
        public static void Working_with_default_values_5()
        {
            Console.WriteLine($">>>> Sample: {nameof(Working_with_default_values_5)}");
            Console.WriteLine();

            Helpers.RecreateCleanDatabase();

            #region Working_with_default_values_5
            using var context = new BlogsContext();

            var userA = new User {
                Name = "Mac"
            };
            var userB = new User {
                Name = "Alice", IsAuthorized = true
            };
            var userC = new User {
                Name = "Baxter", IsAuthorized = false
            };                                                              // Always deny Baxter access!

            context.AddRange(userA, userB, userC);

            context.SaveChanges();
            #endregion

            Console.WriteLine();
        }
    public static void PopulateDatabase()
    {
        using var context = new BlogsContext(quiet: true);

        context.Add(
            new Blog
        {
            Name  = ".NET Blog",
            Posts =
            {
                new Post
                {
                    Title   = "Announcing the Release of EF Core 5.0",
                    Content = "Announcing the release of EF Core 5.0, a full featured cross-platform..."
                },
                new Post
                {
                    Title   = "Announcing F# 5",
                    Content = "F# 5 is the latest version of F#, the functional programming language..."
                },
            }
        });

        context.SaveChanges();
    }
        public ActionResult Create(Blog blog)
        {
            if (ModelState.IsValid)
            {
                db.Blogs.Add(blog);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(blog));
        }
Beispiel #7
0
        public IActionResult Post([FromBody] BlogDto blog)
        {
            var blogEntity = new Blog
            {
                // HTMLSanitizer extracts all tags that should not be allowed to exist
                Title   = _htmlSanitizer.Sanitize(blog.Title),
                Content = _htmlSanitizer.Sanitize(blog.Content)
            };

            _blogsContext.Add(blogEntity);
            _blogsContext.SaveChanges();

            return(Created("Get", new  { id = blogEntity.Id }));
        }
Beispiel #8
0
    public static void Main()
    {
        #region RegisterDiagnosticListener
        DiagnosticListener.AllListeners.Subscribe(new DiagnosticObserver());
        #endregion

        using (var context = new BlogsContext())
        {
            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();

            context.Add(
                new Blog
            {
                Name  = "EF Blog",
                Posts =
                {
                    new Post {
                        Title = "EF Core 3.1!"
                    },
                    new Post {
                        Title = "EF Core 5.0!"
                    }
                }
            });

            context.SaveChanges();
        }

        using (var context = new BlogsContext())
        {
            var blog = context.Blogs.Include(e => e.Posts).Single();

            blog.Name = "EF Core Blog";
            context.Remove(blog.Posts.First());
            blog.Posts.Add(new Post {
                Title = "EF Core 6.0!"
            });

            context.SaveChanges();
        }
        #endregion
    }
        public static void PopulateDatabase()
        {
            using var context = new BlogsContext(quiet: true);

            context.AddRange(
                new Blog
            {
                Name  = ".NET Blog",
                Posts =
                {
                    new Post
                    {
                        Title   = "Announcing the Release of EF Core 5.0",
                        Content = "Announcing the release of EF Core 5.0, a full featured cross-platform..."
                    },
                    new Post
                    {
                        Title   = "Announcing F# 5",
                        Content = "F# 5 is the latest version of F#, the functional programming language..."
                    },
                },
            },
                new Blog
            {
                Name  = "Visual Studio Blog",
                Posts =
                {
                    new Post
                    {
                        Title   = "Disassembly improvements for optimized managed debugging",
                        Content =
                            "If you are focused on squeezing out the last bits of performance for your .NET service or..."
                    },
                    new Post
                    {
                        Title   = "Database Profiling with Visual Studio",
                        Content = "Examine when database queries were executed and measure how long the take using..."
                    },
                }
            });

            context.SaveChanges();
        }
Beispiel #10
0
    public static void Main()
    {
        #region Demonstration
        using (var context = new BlogsContext())
        {
            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();

            context.Add(
                new Blog
            {
                Id    = 1,
                Name  = "EF Blog",
                Posts =
                {
                    new Post {
                        Id = 1, Title = "EF Core 3.1!"
                    },
                    new Post {
                        Id = 2, Title = "EF Core 5.0!"
                    }
                }
            });

            context.SaveChanges();
        }

        using (var context = new BlogsContext())
        {
            var blog = context.Blogs.Include(e => e.Posts).Single();

            blog.Name = "EF Core Blog";
            context.Remove(blog.Posts.First());
            blog.Posts.Add(new Post {
                Id = 3, Title = "EF Core 6.0!"
            });

            context.SaveChanges();
        }
        #endregion
    }
    public static async Task Main()
    {
        await CreateDatabases();

        #region Program
        // Insert, update, and delete some entities

        using (var context = new BlogsContext())
        {
            context.Add(
                new Blog {
                Name = "EF Blog", Posts = { new Post {
                                                Title = "EF Core 3.1!"
                                            }, new Post{
                                                Title = "EF Core 5.0!"
                                            } }
            });

            await context.SaveChangesAsync();
        }

        using (var context = new BlogsContext())
        {
            var blog = context.Blogs.Include(e => e.Posts).Single();

            blog.Name = "EF Core Blog";
            context.Remove(blog.Posts.First());
            blog.Posts.Add(new Post {
                Title = "EF Core 6.0!"
            });

            context.SaveChanges();
        }

        // Do an insert that will fail

        using (var context = new BlogsContext())
        {
            try
            {
                context.Add(new Post {
                    Id = 3, Title = "EF Core 3.1!"
                });

                await context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
            }
        }

        // Look at the audit trail

        using (var context = new AuditContext("DataSource=audit.db"))
        {
            foreach (var audit in context.SaveChangesAudits.Include(e => e.Entities).ToList())
            {
                Console.WriteLine(
                    $"Audit {audit.AuditId} from {audit.StartTime} to {audit.EndTime} was{(audit.Succeeded ? "" : " not")} successful.");

                foreach (var entity in audit.Entities)
                {
                    Console.WriteLine($"  {entity.AuditMessage}");
                }

                if (!audit.Succeeded)
                {
                    Console.WriteLine($"  Error: {audit.ErrorMessage}");
                }
            }
        }
        #endregion
    }
Beispiel #12
0
        private void SeedData()
        {
            // Insert seed data into the database using one instance of the context
            using (var context = new BlogsContext(_dbContextOptions))
            {
                var authorId  = new Guid();
                var userId    = new Guid();
                var blogId    = new Guid();
                var postId    = new Guid();
                var commentId = new Guid();

                var blogs = new List <Blog>
                {
                    new Blog()
                    {
                        Name  = "Dummy blog",
                        Posts = new List <Post>()
                        {
                            new Post()
                            {
                                PostId   = new Guid(),
                                BlogId   = blogId,
                                Comments = null,
                                Content  = "blog post",
                                Title    = "blog post title"
                            }
                        },
                        AuthorId = authorId,
                        BlogId   = blogId
                    }
                };

                foreach (var b in blogs)
                {
                    context.Blogs.Add(b);
                }

                var authors = new List <Author>
                {
                    new Author()
                    {
                        AuthorId = authorId,
                        UserId   = userId,
                        Name     = "AuthorFoo"
                    }
                };

                foreach (var a in authors)
                {
                    context.Authors.Add(a);
                }

                var users = new List <User>
                {
                    new User()
                    {
                        Password = "******",
                        UserId   = userId,
                        Username = "******"
                    }
                };

                foreach (var u in users)
                {
                    context.Users.Add(u);
                }

                var comments = new List <Comment>()
                {
                    new Comment()
                    {
                        AuthorName = "fooCommentator",
                        CommentId  = commentId,
                        Content    = "first comment",
                        CreatedOn  = DateTime.Now,
                        Email      = "*****@*****.**",
                        PostId     = postId
                    }
                };

                foreach (var c in comments)
                {
                    context.Comments.Add(c);
                }

                var posts = new List <Post>
                {
                    new Post
                    {
                        PostId    = postId,
                        BlogId    = blogId,
                        Comments  = comments,
                        Createdon = DateTime.Now,
                        Content   = "Dummy post content",
                        Title     = "Dummy post title"
                    },
                    new Post
                    {
                        PostId    = new Guid(),
                        BlogId    = blogId,
                        Comments  = null,
                        Createdon = DateTime.Now,
                        Content   = "Dummy post content",
                        Title     = "Dummy post title"
                    }
                };

                foreach (var p in posts)
                {
                    context.Posts.Add(p);
                }

                context.SaveChanges();
                blogsContext = context;
            }
        }
Beispiel #13
0
 public void Add(Post model)
 {
     model.Createdon = DateTime.Now;
     _blogsContext.Posts.Add(model);
     _ = _blogsContext.SaveChanges();
 }