Skip to content

Invalid configuration when scaffolding a manytomany table with underscore in fieldname #29563

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
MariovanZeist opened this issue Nov 15, 2022 · 3 comments

Comments

@MariovanZeist
Copy link

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 BlogPost (
  Blog_Id int NOT NULL CONSTRAINT [FK_BlogPost_Blogs] REFERENCES Blogs ON DELETE CASCADE,
  Post_Id int NOT NULL CONSTRAINT [FK_BlogPost_Posts] REFERENCES Posts ON DELETE CASCADE,
  CONSTRAINT [PK_BlogPost] PRIMARY KEY (Blog_Id, Post_Id)
)
go 

(Note the field names are Blog_Id and Post_Id, also the name of the ManyToMany table is singular to avoid #29544)

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",
             r => r.HasOne<Post>().WithMany()
                 .HasForeignKey("PostId")
                 .HasConstraintName("FK_BlogPost_Posts"),
             l => l.HasOne<Blog>().WithMany()
                 .HasForeignKey("BlogId")
                 .HasConstraintName("FK_BlogPost_Blogs"),
             j =>
             {
                 j.HasKey("BlogId", "PostId");
                 j.ToTable("BlogPost");
             });
 });

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]
    INNER JOIN [Posts] AS [p] ON [b0].[PostId] = [p].[Id] -- PostId is invalid name should be Post_Id
) AS [t] ON [b].[Id] = [t].[BlogId]

Which results in an exception:
Microsoft.Data.SqlClient.SqlException: 'Invalid column name 'PostId'.

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)

@ErikEJ
Copy link
Contributor

ErikEJ commented Nov 15, 2022

Could be related to #29450

@bricelam
Copy link
Contributor

bricelam commented Dec 6, 2022

I think this is the same underlying issue as #29634

@bricelam
Copy link
Contributor

bricelam commented Dec 7, 2022

Confirmed.
Duplicate of #29634

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants