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
Support "unconstrained" foreign key relationships #13146
EF Core uses a "foreign key" property that is matched to a "principal key" to define a relationship, where one or both of these may be shadow properties. For relational databases, these relationships are almost always backed by a constraint which means that if an FK property has a value, then there must exist a principal key that matches. We use this information to make decisions/optimizations on which queries to generate. In #9470, we decided to maintain these semantics across providers.
However, there are some cases where the FK and PK exist and define the relationship, but are not constrained in the same way as a relational constraint would do. Specifically, this means that just because an FK property has a value doesn't mean that there is necessarily a matching PK value. This means:
the relationship is always optional, even if the FK isn't nullable
we can't assume that because the FK is set that it means a principal must exist in the database
and therefore we can't assume that getting all the principals will bring in all dependents (same as for optional relationships today)
fixup needs to decide what to do if a relationship is severed but the FK is non-nullable
Reacted by KorsG, Yehuda Ringler, George Green, Bilal Tawfic, Jan Paolo Go, Jukka Snellman, Stian Sandve, Eloy Rubio, jarf70, Marius Gundersen and 149 more
Since there is no responses to this, can I assume there is no solution to this problem? I have this exact requirement but no way to implement it in EF Core. Every migration I now add I have to remove the constraints added in the migration scripts
Since it's mentioned a few times in different issues, are there any plans to support something like this in a future release? It's quite frustrating having no control over created constraints.
@Basssiiie This issue is in the Backlog milestone. This means that it is not planned for the next release (EF Core 5.0). We will re-assess the backlog following the this release and consider this item at that time. However, keep in mind that there are many other high priority features with which it will be competing for resources.
Please vote (👍) for the issue to indicate your interest; based on these votes, this issue is currently 73rd in the list of most voted for features not yet implemented.)
Reacted by lixaotec, Sam Jongenelen, Thibaut Dambacher, Luke Westfall, Song Zhixin, 7CLewis, Boris Marković, w7rus and Erik Strandman
I've needed a solution for this a number of times. This is particularly necessary when synchronizing data between a local and remote database where you can't make a global snapshot to ensure consistent state across everything.
I haven't had a chance to test this but an associate recommended just running a sql script to delete the foreign key constraint and using EF core as is. Not sure if That will work though.
What is the status of this issue? It is the exact problem I am running into.
I have records from a 3rd party system that are mapped to entities in our application.
The 3rd party system tracks employee hours against projects. That system has its own project ids and user ids needed for invoicing in that system. When we import those hour logs into our system they map to our internal Users and projects via the project and user id of the the 3rd party system.
Our tables:
Project
id : int
ImportProjectId : string
Other project columns...
User
Id : int
ImportProjectId : string
Other user columns...
3rdPartyHours
Date : datetime
UserId : string
ProjectId : string
Other 3rd party columns...
Since the 3rd party hours are imported programmatically, there will be times when a new employee or new project is added to the 3rd party system that has not been created in our system yet. When that happens we have runtime code that identifies the missing User or Project.
The problem is that we need navigation properties from the imported hours to our projects and users. We use the 3rd party project and user ids as navigation properties to our projects and users. Since EF creates foreign key constraints we get errors when the 3rd party hours are imported and the new user or project has not been created and associated in our system yet.
The functionality would be much more useful if the 3rd party hour entities allowed for navigation properties that could be null. As stated before, we can handle that situation at runtime and notify the user that a new project or user needs to be added in our system to map to the 3rd party project or user.
@lwestfall Note that this issue is not about EF Core creating the constraints in the database--that is tracked by #15854. Rather this issue is about allowing EF to work with different foreign key semantics. Simply removing the database constraint, while required for this, is not sufficient to make EF Core work with these different semantics.
@Dreamescaper I think we'd need a full proposal for the exact behavior you propose implementing; a simple IsConstrained(false) doesn't tell us much about what you exactly have in mind. Note that if what you want is for EF to simply not create foreign key constraints in migrations, that's #15854.
In any case, looping in @AndriySvyryd who has more knowledge on mapping/modeling.
No, simply avoiding FKs is not enough, I need EF to treat this relation as optional (i.e. generate LEFT JOINs when used with Include).
I suggest to add IsConstrained method to ReferenceCollectionBuilder, which would enforce the folowing behavior, if 'false' is provided:
No FK constrains are added in the DB
EF Core treats the relationship as optional (generates LEFT JOINs, not INNER JOINs)
Doesn't change the nullability of FK columns (could be both nullable and non-nullable).
I have achieved that via the following workaround, but it is really hacky, I would prefer to replace it with a built in implementation. #13146 (comment)
IMO, the most challenging part of this issue is identifying all the places (mostly change tracking, but also query and updates) where EF assumes that some principal must exist if a dependent FK exists, which has been the case until now. That being said, it shouldn't be that challenging for someone willing to do a detail-oriented job on the code, for which AI can help.
I think this would be a valuable addition to EF Core--I hope you can get to it, @Dreamescaper.
I had the same issue with a TPH inheritance and just one column modeling the FK.
Depending on the concrete Type, the FK would go to a different table.
I could model and query this without problems, but the Migration would generate one Foreign Key for each type which would go to different tables.
Using the code from @Dreamescaper in #13146 (comment), I was able to simply not generate the FK in the migration, but keep the query capabilities.
Like wertzui I had a similar issue when using TPH inheritance, see #15854 (comment). In my case, it also adds a superfluous unique index in addition to the foreign key.
@Dreamescaper Thank you for your IsConstrained extension. When using the following relationship configuration:
Activity
mariusGundersen commentedon Nov 11, 2019
Since there is no responses to this, can I assume there is no solution to this problem? I have this exact requirement but no way to implement it in EF Core. Every migration I now add I have to remove the constraints added in the migration scripts
AndriySvyryd commentedon Nov 11, 2019
@mariusGundersen That's the best workaround until #2725 is implemented
Basssiiie commentedon Oct 21, 2020
Since it's mentioned a few times in different issues, are there any plans to support something like this in a future release? It's quite frustrating having no control over created constraints.
Thank you for your time! :)
ajcvickers commentedon Oct 21, 2020
@Basssiiie This issue is in the Backlog milestone. This means that it is not planned for the next release (EF Core 5.0). We will re-assess the backlog following the this release and consider this item at that time. However, keep in mind that there are many other high priority features with which it will be competing for resources.
Please vote (👍) for the issue to indicate your interest; based on these votes, this issue is currently 73rd in the list of most voted for features not yet implemented.)
TonyValenti commentedon Mar 13, 2021
I've needed a solution for this a number of times. This is particularly necessary when synchronizing data between a local and remote database where you can't make a global snapshot to ensure consistent state across everything.
lixaotec commentedon Mar 15, 2021
@TonyValenti how did you workedaround?
TonyValenti commentedon Mar 15, 2021
I haven't had a chance to test this but an associate recommended just running a sql script to delete the foreign key constraint and using EF core as is. Not sure if That will work though.
qsdfplkj commentedon Mar 15, 2021
As a workaround we consider using placeholders for this. Tough implications of this could be that all values should be nullable.
drewberk commentedon Oct 7, 2022
What is the status of this issue? It is the exact problem I am running into.
I have records from a 3rd party system that are mapped to entities in our application.
The 3rd party system tracks employee hours against projects. That system has its own project ids and user ids needed for invoicing in that system. When we import those hour logs into our system they map to our internal Users and projects via the project and user id of the the 3rd party system.
Our tables:
Project
User
3rdPartyHours
Since the 3rd party hours are imported programmatically, there will be times when a new employee or new project is added to the 3rd party system that has not been created in our system yet. When that happens we have runtime code that identifies the missing User or Project.
The problem is that we need navigation properties from the imported hours to our projects and users. We use the 3rd party project and user ids as navigation properties to our projects and users. Since EF creates foreign key constraints we get errors when the 3rd party hours are imported and the new user or project has not been created and associated in our system yet.
The functionality would be much more useful if the 3rd party hour entities allowed for navigation properties that could be null. As stated before, we can handle that situation at runtime and notify the user that a new project or user needs to be added in our system to map to the 3rd party project or user.
ajcvickers commentedon Oct 11, 2022
@lwestfall Note that this issue is not about EF Core creating the constraints in the database--that is tracked by #15854. Rather this issue is about allowing EF to work with different foreign key semantics. Simply removing the database constraint, while required for this, is not sufficient to make EF Core work with these different semantics.
lwestfall commentedon Oct 11, 2022
@ajcvickers I appreciate the correction, I've moved my comment to #15854 where it's more relevant
20 remaining items
roji commentedon Feb 13, 2026
@Dreamescaper I think we'd need a full proposal for the exact behavior you propose implementing; a simple
IsConstrained(false)doesn't tell us much about what you exactly have in mind. Note that if what you want is for EF to simply not create foreign key constraints in migrations, that's #15854.In any case, looping in @AndriySvyryd who has more knowledge on mapping/modeling.
Dreamescaper commentedon Feb 15, 2026
No, simply avoiding FKs is not enough, I need EF to treat this relation as optional (i.e. generate LEFT JOINs when used with Include).
I suggest to add IsConstrained method to ReferenceCollectionBuilder, which would enforce the folowing behavior, if 'false' is provided:
I have achieved that via the following workaround, but it is really hacky, I would prefer to replace it with a built in implementation.
#13146 (comment)
ajcvickers commentedon Feb 16, 2026
IMO, the most challenging part of this issue is identifying all the places (mostly change tracking, but also query and updates) where EF assumes that some principal must exist if a dependent FK exists, which has been the case until now. That being said, it shouldn't be that challenging for someone willing to do a detail-oriented job on the code, for which AI can help.
I think this would be a valuable addition to EF Core--I hope you can get to it, @Dreamescaper.
wertzui commentedon Feb 18, 2026
I had the same issue with a TPH inheritance and just one column modeling the FK.
Depending on the concrete Type, the FK would go to a different table.
I could model and query this without problems, but the Migration would generate one Foreign Key for each type which would go to different tables.
Using the code from @Dreamescaper in #13146 (comment), I was able to simply not generate the FK in the migration, but keep the query capabilities.
mguinness commentedon Feb 25, 2026
Like wertzui I had a similar issue when using TPH inheritance, see #15854 (comment). In my case, it also adds a superfluous unique index in addition to the foreign key.
@Dreamescaper Thank you for your
IsConstrainedextension. When using the following relationship configuration:modelBuilder.Entity<Blog>().HasOne(c => c.Favorite).WithOne().HasForeignKey<FavoriteBlog>(a => a.EntityId);I don't suppose there is a way to eliminate that unique index when using your extension method on the relationship?
Support "unconstrained" foreign key relationships (dotnet#13146)
Address PR review feedback (dotnet#13146)
Support "unconstrained" foreign key relationships (dotnet#13146)
Address PR review feedback (dotnet#13146)
Support "unconstrained" foreign key relationships (#38361)