Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- if (!ctx.Posts.Any()) {
- Tag tag = new Tag() {
- Name = "Test1"
- };
- User user = new User() {
- UserName = "TestUser",
- Email = "test1@test1.bg",
- Password = Extensions.PasswordHash("abv123456", config["AppSettings:PasswordSalt"]),
- Role = UserRoles.Member
- };
- ctx.Users.Add(user);
- Post post = new Post() {
- Title = "Test Post",
- Description = "Description post test",
- Likes = 5,
- User = user,
- CreateOn = DateTime.Now,
- LastEditOn = DateTime.Now
- };
- PostTag posttags = new PostTag() {
- Post = post,
- Tag = tag
- };
- ctx.PostTag.Add(posttags);
- ctx.SaveChanges();
- };
- public IActionResult GetAllPost() {
- var posts = _ctx.Posts
- .Include(u => u.User)
- .ToList();
- return Json(Newtonsoft.Json.JsonConvert.SerializeObject(posts));
- }
- services.AddMvc().AddJsonOptions(opts => {
- opts.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
- });
- protected override void OnModelCreating(ModelBuilder modelBuilder) {
- // set unique email and username
- modelBuilder.Entity<User>()
- .HasIndex(u => new { u.Email, u.UserName })
- .IsUnique();
- // set unique tag name
- modelBuilder.Entity<Tag>()
- .HasIndex(t => t.Name)
- .IsUnique();
- modelBuilder.Entity<Post>()
- .HasOne(p => p.User)
- .WithMany(u => u.Posts);
- modelBuilder.Entity<User>()
- .HasMany(u => u.Comments)
- .WithOne(u => u.User);
- // post tag many-to-many rel
- modelBuilder.Entity<PostTag>()
- .HasKey(pt => new { pt.PostUID, pt.TagUID });
- modelBuilder.Entity<PostTag>()
- .HasOne(pt => pt.Post)
- .WithMany(p => p.PostTags)
- .HasForeignKey(pt => pt.PostUID);
- modelBuilder.Entity<PostTag>()
- .HasOne(pt => pt.Tag)
- .WithMany(p => p.PostTags)
- .HasForeignKey(pt => pt.TagUID);
- }
- return Json(Newtonsoft.Json.JsonConvert.SerializeObject(posts));
- return Json(posts);
Add Comment
Please, Sign In to add comment