Skip to content

Detect simple join tables in reverse engineering and create many-to-many relationships #22475

Closed

Description

@ajcvickers
No description provided.

Activity

  1. self-assigned this
    on Sep 11, 2020
  2. ajcvickers commented on Sep 11, 2020

    @ajcvickers
    ContributorAuthor

    Notes from triage:

    • The pri-zero here is that a database created by EF6 with many-to-many relationships should reverse-engineer to EF Core with many-to-many relationships. Specifically, the join table must contain only columns for the two FKs and these columns must also form the primary key. If the table has a separate PK or any payload columns, then it should not be considered many-to-many.
    • Meeting the EF6 scenario should also mean that simple, fully by-convention many-to-many relationships created by EF Core will round-trip.
    • It's too late to do this for EF Core 5.0.

    @ErikEJ Might you consider doing this in the EF Core Power Tools? That would make something available for 5.0. Also, in the future, if you want to do the PR for here, that would be awesome! 😁

  3. added this to the Backlog milestone on Sep 11, 2020
  4. ErikEJ commented on Sep 11, 2020

    @ErikEJ
    Contributor

    @ajcvickers I assume that would require changes to code generation, then?

  5. ajcvickers commented on Sep 11, 2020

    @ajcvickers
    ContributorAuthor

    @ErikEJ Yes, it probably would. @bricelam?

  6. ErikEJ commented on Sep 11, 2020

    @ErikEJ
    Contributor

    Ok - I have already reluctantly pulled in some Internal code anyway. Happy to take a PR for this!!

  7. smitpatel commented on Sep 11, 2020

    @smitpatel
    Contributor

    It would probably require some changes to code gen. Currently there is no processing of SkipNavigations in code gen at all. I think best place to identify and add skip navigation would be RelationalScaffoldingModelFactory (now we are deep in internal territory lol) to add skip navs to model and code gen will handle it as such.

  8. ErikEJ commented on Sep 12, 2020

    @ErikEJ
    Contributor

    Hmmm.. where would I specify the table name (since it most likely will not match convention)

    Assume in fluent config, but how, since there is no EntityType to refer to??

  9. smitpatel commented on Sep 12, 2020

    @smitpatel
    Contributor
    modelBuilder.Entity<One>().HasMany(e => e.TwoSkip).WithMany(e => e.OneSkip).UsingEntity(e => e.ToTable("tableName"));

    EF will fill in actual entity type appropriately, whatever that type would be by convention. (Likely Dictionary<string, object>)
    (Untested code)

  10. bmoteria commented on Sep 16, 2020

    @bmoteria

    @smitpatel The provided solution doesn't seem to work in my scenario as the table "FeatureVehicle" contains two columns which has underscore ("Feature_ID" and "Vehicle_VehicleID"). (cc @ajcvickers)

    When query is executed it throws following exception:

    Microsoft.EntityFrameworkCore.Query: Error: An exception occurred while iterating over the results of a query for context type '<PRODUCT>.Data.Context.<PRODUCT>DbContext'.
    Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid column name 'FeaturesID'.
    Invalid column name 'VehiclesID'.
    Invalid column name 'VehiclesID'.
    Invalid column name 'VehiclesID'.
    Invalid column name 'FeaturesID'.
       at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
       at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
       at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
       at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData()
       at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
       at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean isAsync, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
       at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method)
       at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
       at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
       at Microsoft.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
       at System.Data.Common.DbCommand.ExecuteReader()
       at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
       at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)
       at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
       at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
    ClientConnectionId:76b39b9f-06db-43a9-ae78-d7820dd60584
    

    Here are my entities:

    public partial class Vehicle
    {
         ....
         public ICollection<Feature> Features { get; set; }
    }
    
    public partial class Feature
    {
         ....
         public ICollection<Vehicle> Vehicles { get; set; }
    }
    
  11. smitpatel commented on Sep 16, 2020

    @smitpatel
    Contributor

    @bmoteria - Your issue is not related to the issue you are posting on. Please avoid off-topic discussions. Your column names in the join entity does not match what is generated conventionally, so you will need to configure them manually using HasColumnName.

  12. 54 remaining items

  13. ErikEJ commented on Nov 24, 2021

    @ErikEJ
    Contributor

    @moritzinio please open a new issue, and share your database schema.

  14. moritzinio commented on Nov 24, 2021

    @moritzinio

    @ErikEJ I will tomorrow thank you.

  15. sommmen commented on Feb 22, 2022

    @sommmen
  16. smitpatel commented on Mar 11, 2022

    @smitpatel
    Contributor
  17. Scionn commented on Jul 12, 2022

    @Scionn

    @ajcvickers hiya this docs page https://docs.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key#many-to-many

    Points to this workitem which seems to be closed. Is this now fixed or not? perhaps the docs should be updated?

    I don't think its SOLVED, we have the same problem today with the latest version of EF core 6.0.6 (at the moment) scaffolding a Postgresql database with two m-2-m tables...

  18. ajcvickers commented on Jul 12, 2022

    @ajcvickers
    ContributorAuthor

    @Scionn Please open a new issue and post the schema and command that results in the issue so that we can investigate.

  19. RicardOlivo commented on Apr 20, 2023

    @RicardOlivo

    Maybe missing something here, but I'm baffled at how or why would Microsoft arbitrarily force a set of rules and decide which and when a table will be reverse engineered and when to skip it, without even a flag to supress it. Is there a way to full scaffold using net 6 without this nonsense, other than doing it by hand? thanks

  20. ErikEJ commented on Apr 20, 2023

    @ErikEJ
    Contributor

    @RicardOlivo Yes, just use EF Core Power Tools!

  21. tuyendam00 commented on Jun 8, 2023

    @tuyendam00

    I still want ef core gen class mapping many-many in net 6.0, how to do it
    I want:
    modelBuilder.Entity(
    entity =>
    {
    entity.HasKey(e => new { e.GenerateProjectId, e.ProgrammingLanguageId });

                entity.ToTable("GenerateProjectProgrammingLanguageMapping", "MDM");
    
                entity.HasOne(d => d.GenerateProject)
                    .WithMany(p => p.GenerateProjectProgrammingLanguageMapping)
                    .HasForeignKey(d => d.GenerateProjectId)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_GenerateProjectProgrammingLanguageMapping_GenerateProject");
    
                entity.HasOne(d => d.ProgrammingLanguage)
                    .WithMany(p => p.GenerateProjectProgrammingLanguageMapping)
                    .HasForeignKey(d => d.ProgrammingLanguageId)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_GenerateProjectProgrammingLanguageMapping_ProgrammingLanguage");
            });
    

    Ef gen:
    entity.HasMany(d => d.ProgrammingLanguages)
    .WithMany(p => p.GenerateProjects)
    .UsingEntity<Dictionary<string, object>>(
    "GenerateProjectProgrammingLanguageMapping",
    l => l.HasOne().WithMany().HasForeignKey("ProgrammingLanguageId").OnDelete(DeleteBehavior.ClientSetNull).HasConstraintName("FK_GenerateProjectProgrammingLanguageMapping_ProgrammingLanguage"),
    r => r.HasOne().WithMany().HasForeignKey("GenerateProjectId").OnDelete(DeleteBehavior.ClientSetNull).HasConstraintName("FK_GenerateProjectProgrammingLanguageMapping_GenerateProject"),
    j =>
    {
    j.HasKey("GenerateProjectId", "ProgrammingLanguageId");

                            j.ToTable("GenerateProjectProgrammingLanguageMapping");
                        });
    
  22. RicardOlivo commented on Jun 8, 2023

    @RicardOlivo

    @tuyendam00 I did it using net core 3.1, then copy/pasted into 6. Sad I know.

  23. ErikEJ commented on Jun 8, 2023

    @ErikEJ
    Contributor

    @tuyendam00 @RicardOlivo Just use EF Core Power Tools, it has an option to generate the actual entities

  24. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions