在asp.net core 2和EF core中创建带有标签的多对多关系的帖子

时间:2018-09-26 21:23:27

标签: c# entity-framework-core asp.net-core-2.1

对于我的博客文章,我有一些关于多对多关系的问题。如果我将MakaleId和EtiketId手动添加到MakaleEtiket表中,则可以,但是我需要在创建博客文章时执行此步骤。我希望有人能帮助我,在此先感谢。 这里有一些可变翻译;

Etiket =标签

Makale =文章

我的实体

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Bukalemur.WebUI.Entity
{
    public class Etiket
    {
        public int EtiketId { get; set; }
        public string EtiketAdi { get; set; }


        public ICollection<MakaleEtiket> MakaleEtikets { get; } = new List<MakaleEtiket>(); 
    }
}

我的背景

using Bukalemur.WebUI.Entity;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Bukalemur.WebUI.Repository.EntityFramework
{
    public class MakaleContext:DbContext
    {
        public MakaleContext(DbContextOptions<MakaleContext> options):base(options)
        {

        }

        public DbSet<Abone> Abones { get; set; }
        public DbSet<Makale> Makales { get; set; }
        public DbSet<Kategori> Kategoris { get; set; }
        public DbSet<Etiket> Etikets { get; set; }
        public DbSet<MakaleEtiket> MakaleEtikets { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<MakaleEtiket>().HasKey(pk => new { pk.MakaleId, pk.EtiketId });

        }
    }
}

我的控制器创建动作

[HttpGet]
public IActionResult AddOrUpdate(int? id)
{
    ViewBag.Kategoriler = new SelectList(kategoriRepository.GetAll(), "KategoriId", "KategoriAdi");
    if (id == null)
    {
        return View(new Makale());
    }
    else
    {
        return View(makaleRepository.GetById((int)id));
    }
}

[HttpPost]
public async Task<IActionResult> AddorUpdate(Makale entity, IFormFile file, string etiketler)
{

    if (ModelState.IsValid)
    {
        if (etiketler != null)
        {
            string[] etiketdizi = etiketler.Split(',');
            foreach (var item in etiketdizi)
            {
                var yenietiket = new Etiket { EtiketAdi = item };

            }

        }

        var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\img", file.FileName);
        using (var stream = new FileStream(path, FileMode.Create))
        {
            await file.CopyToAsync(stream);
        }
        entity.Image = file.FileName;
        makaleRepository.SaveMakale(entity);
        {

        };
        TempData["message"] = $"{entity.Baslik} kayıt edildi.";
        return RedirectToAction("Index", "Admin");


    }
    ViewBag.Kategoriler = new SelectList(kategoriRepository.GetAll(), "KategoriId", "KategoriAdi");
    return View(entity);
}

0 个答案:

没有答案