Home > OS >  Adding collection of items in Many to Many Relationship in ASP.NET Core MVC Problem (Code first)
Adding collection of items in Many to Many Relationship in ASP.NET Core MVC Problem (Code first)

Time:01-30

I have two Entities that have many To many relationship, Book and Tags asp Created automatically a table for the two entities, Using the code first approach

  1. I am trying to add a collection of tags in the book creation, but the tag items are null also there is (select asp-for="Tags" ) but it shows me null in [httppost]create.

  2. I tried to add it in through context as it catches the values of tags I add, but there is an error

    cannot convert ......dbset<> to Models.tags

Code:

public class Book
{
    public int BookID { get; set; }
    [Required]
    public string Name { get; set; } = null!;

    //Navigation property
    public virtual ICollection<Tags>? Tags { get; set; }   
}

public class Tags
{
    public int TagsID { get; set; } 
    public string TagName { get; set; } = null!;

    //Navigation property
    public virtual ICollection<Book>? Book { get; set; }
}

//DB Context
public class BLabContext: DbContext
{
    public DbSet<Book> Book { get; set; }   
    public DbSet<Tags> Tags { get; set; } 
}

// Book Controller
public class BooksController : Controller
{
    private readonly BLabContext _context;

    public BooksController(BLabContext context)
    {
        _context = context;
    }

    // Tags objects
   
    // public ICollection<Tags> Tags { get; set; }
   
    // GET: Books
    public async Task<IActionResult> Index()
    {
        return View(await _context.Book.ToListAsync());
    }

    // GET: Books/Create

(on get ) public IActionResult Create() { ///

  • Related