Skip to content

Invalid singularization when scaffolding a manytomany table #29544

@MariovanZeist

Description

@MariovanZeist

Assume the following Database:

CREATE TABLE Blogs (Id int IDENTITY CONSTRAINT [PK_Blogs] PRIMARY KEY,) 
go 

CREATE TABLE Posts (Id int IDENTITY CONSTRAINT [PK_Posts] PRIMARY KEY,) 
go 

CREATE TABLE BlogPosts (
  BlogId int NOT NULL CONSTRAINT [FK_BlogPosts_Blogs] REFERENCES Blogs ON DELETE CASCADE,
  PostId int NOT NULL CONSTRAINT [FK_BlogPosts_Posts] REFERENCES Posts ON DELETE CASCADE,
  CONSTRAINT [PK_BlogPosts ] PRIMARY KEY (BlogId, PostId)
)
go 

When scaffolding in EF7 the following Configuration will be created.

 modelBuilder.Entity<Blog>(entity =>
 {
     entity.HasMany(d => d.Posts).WithMany(p => p.Blogs)
         .UsingEntity<Dictionary<string, object>>(
             "BlogPost",       //<-note the missing s from the original Tablename(BlogPosts)
             r => r.HasOne<Post>().WithMany()
                 .HasForeignKey("PostId")
                 .HasConstraintName("FK_BlogPosts_Posts"),
             l => l.HasOne<Blog>().WithMany()
                 .HasForeignKey("BlogId")
                 .HasConstraintName("FK_BlogPosts_Blogs"),
             j =>
             {
                 j.HasKey("BlogId", "PostId").HasName("PK_BlogPosts ");
                 //The following line of code is NOT generated (but was generated in earlier versions) and might be what is actually missing here
                 //j.ToTable("BlogPosts");
             });
 });

When executing the following statement:

  var allposts = await ctx.Blogs.SelectMany(b => b.Posts).ToArrayAsync();

The following SQL will be generated:

SELECT [t].[Id]
FROM [Blogs] AS [b]
INNER JOIN (
    SELECT [p].[Id], [b0].[BlogId]
    FROM [BlogPost] AS [b0]    --  <-Invalid table name
    INNER JOIN [Posts] AS [p] ON [b0].[PostId] = [p].[Id]
) AS [t] ON [b].[Id] = [t].[BlogId]

resulting in
Microsoft.Data.SqlClient.SqlException: 'Invalid object name 'BlogPost'.'

EF Core version: 7.0
Database provider: (e.g. Microsoft.EntityFrameworkCore.SqlServer)
Target framework: (e.g. .NET 7.0)
Operating system:
IDE: (e.g. Visual Studio 2022 17.4)

Metadata

Metadata

Assignees

Type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions