You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Detect simple join tables in reverse engineering and create many-to-many relationships #22475
Reacted by Brice Lambson, saxmaster79, Chris, Sentai, Mikhail Khalizev, gabrielcapanogyp, Sebastian Klatte, Sergio Oporto, Adam Stachowicz, Leosori and 11 more
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! 😁
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.
@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; }
}
@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.
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...
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
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 });
Activity
ajcvickers commentedon Sep 11, 2020
Notes from triage:
@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! 😁
ErikEJ commentedon Sep 11, 2020
@ajcvickers I assume that would require changes to code generation, then?
ajcvickers commentedon Sep 11, 2020
@ErikEJ Yes, it probably would. @bricelam?
ErikEJ commentedon Sep 11, 2020
Ok - I have already reluctantly pulled in some Internal code anyway. Happy to take a PR for this!!
smitpatel commentedon Sep 11, 2020
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.
ErikEJ commentedon Sep 12, 2020
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??
smitpatel commentedon Sep 12, 2020
EF will fill in actual entity type appropriately, whatever that type would be by convention. (Likely Dictionary<string, object>)
(Untested code)
bmoteria commentedon Sep 16, 2020
@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:
Here are my entities:
smitpatel commentedon Sep 16, 2020
@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.
54 remaining items
ErikEJ commentedon Nov 24, 2021
@moritzinio please open a new issue, and share your database schema.
moritzinio commentedon Nov 24, 2021
@ErikEJ I will tomorrow thank you.
sommmen commentedon Feb 22, 2022
@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?
smitpatel commentedon Mar 11, 2022
Filed dotnet/EntityFramework.Docs#3760
Scionn commentedon Jul 12, 2022
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...
ajcvickers commentedon Jul 12, 2022
@Scionn Please open a new issue and post the schema and command that results in the issue so that we can investigate.
RicardOlivo commentedon Apr 20, 2023
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
ErikEJ commentedon Apr 20, 2023
@RicardOlivo Yes, just use EF Core Power Tools!
tuyendam00 commentedon Jun 8, 2023
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 });
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");
RicardOlivo commentedon Jun 8, 2023
@tuyendam00 I did it using net core 3.1, then copy/pasted into 6. Sad I know.
ErikEJ commentedon Jun 8, 2023
@tuyendam00 @RicardOlivo Just use EF Core Power Tools, it has an option to generate the actual entities