如何在 PostCategory 中添加带有 PostId 和 CategoryId 的博客 post?

How can I add Blog post with PostId and CategoryId in PostCategory?

我有一个问题。我在 mvc 核心上做博客。我创建了 3 entities.Post、Category 和 PostCategory。当我想创建博客 post 时,我想在 PostCategory 表上添加 PostId 和 CategoryId.I 完成 EditPost 的工作,但我没有使用 CreatePost 方法。我需要帮助。让我展示一下我的代码。

这是我的实体。

public class Post : IEntity
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Text { get; set; }
    public DateTime DateTime { get; set; }
    public string ImageUrl { get; set; }

    public List<PostCategory> PostCategories { get; set; }
}


  public class Category : IEntity
{
    public int Id { get; set; }
    public string Name { get; set; }

    public List<PostCategory> PostCategories { get; set; }
}


 public class PostCategory:IEntity
{
    public int PostId { get; set; }
    public Post Post { get; set; }

    public int CategoryId { get; set; }
    public Category Category { get; set; }
}

我在 BlogContext 中完成了设置

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<PostCategory>()
            .HasKey(c => new { c.CategoryId, c.PostId });

    }

    public DbSet<Post> Posts { get; set; }
    public DbSet<Category> Categories { get; set; }

我想在 EfCorePostDal 中显示 PostService。(我想我应该在这里修复)

 public void Create(Post entity, int [] categoryIds)
    {
        using (var context = new BlogContext())
        {
            var post = context.Posts
                .Include(x => x.PostCategories)
                .ThenInclude(x => x.Category)
                .FirstOrDefault();
           
            if (post != null)
            {
                post.Title = entity.Title;
                post.Text = entity.Text;
                post.ImageUrl = entity.ImageUrl;
                post.DateTime = entity.DateTime;

                post.PostCategories = categoryIds.Select(categoryId => new PostCategory()
                {
                    CategoryId = categoryId,
                    PostId = entity.Id
                }).ToList();

            }
            context.SaveChanges();
        }
    }

这是我的AdminController.I尝试采取categoryIds.When我签入debug.I可以做it.I顺便在WebUI的PostModel中创建

public ActionResult CreatePost()
    {
        ViewBag.Categories = _categoryService.GetAll();
        return View(new PostModel() { });
    }


    [HttpPost]
    public async Task<ActionResult> CreatePost(PostModel model, IFormFile file,int[] categoryIds)
    {
        if (ModelState.IsValid)
        {
            var entity = new Post
            {
                Title = model.Title,
                Text = model.Text,
                DateTime = model.DateTime,
                ImageUrl = model.ImageUrl,
            };
            if (file != null)
            {
                entity.ImageUrl = file.FileName;

                var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\img", file.FileName);
                using (var stream = new FileStream(path, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
            }
            if (_postService.Create(entity,categoryIds))
            {
                return RedirectToAction("ListPosts", "Admin");
            }

            return View(model);
        }
        ViewBag.Categories = _categoryService.GetAll();
        return View(model);
    }

我的 PostModel

 public class PostModel
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Text { get; set; }
    public DateTime DateTime { get; set; }
    public string ImageUrl { get; set; }
    public List<Category> SelectedCategories { get; set; }

}

这是我的 Createpost.cshtml

<form asp-controller="Admin" asp-action="CreatePost" method="post" enctype="multipart/form-data">
<div asp-validation-summary="All" class="text-danger"></div>
<input type="hidden" name="Id" value="@Model.Id" />
<div class="row">
    <div class="col-md-8">
        <div class="form-group row">
            <label asp-for="Title" class="col-md-2 col-form-label"></label>
            <div class="col-md-10">
                <input asp-for="Title" value="" class="form-control" />
            </div>
        </div>
        <div class="form-group row">
            <label asp-for="DateTime" class="col-md-2 col-form-label"></label>
            <div class="col-md-10">
                <input asp-for="DateTime" value="" class="form-control" />
            </div>
        </div>
        <div class="form-group row">
            <label asp-for="ImageUrl" class="col-md-2 col-form-label"></label>
            <div class="col-md-10">
                <input type="file" name="file" value="" />
            </div>
        </div>
    </div>
    <div class="col-md-4">
        @foreach (var item in (List<Category>)ViewBag.Categories)
        {
            <div class="form-check">
                <input type="checkbox"
                       name="categoryIds"
                       value="@item.Id"
                       class="form-check-input"
                       id="category@(item.Id)">
                <label class="form-check-label" for="category@(item.Id)">@item.Name</label>
            </div>
        }

    </div>
    <div class="col-md-12">
        <div class="form-group row">
            <div class="col-md-12">
                <textarea asp-for="Text" class="form-control"></textarea>
            </div>
        </div>
    </div>
</div>
<div class="form-group row">
    <div class="col-md-12">
        <button type="submit" class="btn btn-success btn-block">Share</button>
    </div>
</div>

最后我应该做什么?当我添加 post 时,它不起作用。 (我是新开发者,对我的基本错误深表歉意)

根据您的描述和代码,我发现您更新了 post 而不是创建新的 post 记录。

我建议您可以尝试使用下面的代码来创建新的 post 记录。

注意:我在CreatePost方法中直接使用了带DI的dbcontext,你可以根据我的代码自行修改Create方法。

    [HttpPost]
    public async Task<ActionResult> CreatePost(PostModel model, IFormFile file, int[] categoryIds)
    {

        int[] test = new int[] {1,2,3,4,5 };

        if (ModelState.IsValid)
        {
            var entity = new Post
            {
                Title = model.Title,
                Text = model.Text,
                DateTime = model.DateTime,
                ImageUrl = model.ImageUrl,
        };

            var reparePart1 = test.Select(categoryId => new PostCategory()
            {
                CategoryId = categoryId,
                Post = entity
            }).ToList();


            entity.PostCategories = reparePart1;

            _dbContext.Add(entity);


            _dbContext.SaveChanges();

            if (file != null)
            {
                entity.ImageUrl = file.FileName;

                //var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\img", file.FileName);
                //using (var stream = new FileStream(path, FileMode.Create))
                //{
                //    await file.CopyToAsync(stream);
                //}
            }
            //Create(entity, categoryIds);
            return View(model);
        }
        //ViewBag.Categories = _categoryService.GetAll();
        return View(model);
    }