Click here to Skip to main content
15,883,785 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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")] // Errors: Error, Index is not an attribute class and namespace Name could not be found. 
    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?
Posted
Updated 3-Feb-22 6:36am

1 solution

Quote:
EF Core does not support creating a composite key using the Key attribute. You have to use the Fluent API HasKey() function in EF Core.


Data Annotations: Key Attribute in EF 6 & EF Core[^]

Relationships - EF Core | Microsoft Docs[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900