I have currently two models I've created in Entity Framework Core 5 and a mapping table was created implicitly, unlike EFC 3.1 where we have to make a one-to-many table explicitly.
The tables are named Authors and Books, and between them AuthorBook was created with the ids, FK I believe.
Problem is I need to use AuthorBook in a AuthorBookViewModel as we know, it's already in the database.
What I have tried:
I've tried reverse engineering the database, as if I had created the mapping table using:
Scaffold-Dbcontext "Server=DESKTOP-3M9V0GN\SQLEXPRESS;Database=MagicLib;Trusted_Connection=True;MultipleActiveResultSets=True" Microsoft.EntityFrameworkCore.SqlServer -Outputdir Models -Context TESTCONTEXT -Tables AuthorBook -dataannotations
Originally from:
How to Add An Existing Database Table to a Project with Entity Framework Core - ASP.NET Core - YouTube[
^]
Also:
Working with an Existing Database | Entity Framework Core 101 [2 of 5] - YouTube[
^]
The last one was more helpful for me personally.
The reverse engineering was a success, now it has some errors I could not figure out how to solve:
namespace MagicLib_Model.Models
{
[Table("AuthorBook")]
[Index(nameof(BooksBookId), Name = "IX_AuthorBook_BooksBook_Id")]
public partial class AuthorBook
{
[Key]
[Column("AuthorsAuthor_Id")]
public int AuthorsAuthorId { get; set; }
[Key]
[Column("BooksBook_Id")]
public int BooksBookId { get; set; }
}
}
If I comment out "Index" line I get a
System.InvalidOperationException: 'The entity type 'AuthorBook' has multiple properties with the [Key] attribute. Composite primary keys can only be set using 'HasKey' in 'OnModelCreating'.'
When I open Book View.
My idea was to go back and make myself my own mapping table instead of this hassle.
I know that would work.
How can I make it work, using EFC's code first approach many to many implicitly created table, being it in the db, and not in my Models?