Skip to content

Support "unconstrained" foreign key relationships #13146

Description

@ajcvickers

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

Activity

  1. added this to the Backlog milestone on Aug 28, 2018
  2. mariusGundersen commented on Nov 11, 2019

    @mariusGundersen

    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

  3. AndriySvyryd commented on Nov 11, 2019

    @AndriySvyryd
    Member

    @mariusGundersen That's the best workaround until #2725 is implemented

  4. Basssiiie commented on Oct 21, 2020

    @Basssiiie

    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! :)

  5. ajcvickers commented on Oct 21, 2020

    @ajcvickers
    ContributorAuthor

    @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.)

  6. TonyValenti commented on Mar 13, 2021

    @TonyValenti

    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.

  7. lixaotec commented on Mar 15, 2021

    @lixaotec

    @TonyValenti how did you workedaround?

  8. TonyValenti commented on Mar 15, 2021

    @TonyValenti

    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.

  9. qsdfplkj commented on Mar 15, 2021

    @qsdfplkj

    As a workaround we consider using placeholders for this. Tough implications of this could be that all values should be nullable.

  10. drewberk commented on Oct 7, 2022

    @drewberk

    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.

  11. ajcvickers commented on Oct 11, 2022

    @ajcvickers
    ContributorAuthor

    @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.

  12. lwestfall commented on Oct 11, 2022

    @lwestfall

    @ajcvickers I appreciate the correction, I've moved my comment to #15854 where it's more relevant

  13. 20 remaining items

  14. roji commented on Feb 13, 2026

    @roji
    Member

    @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.

  15. Dreamescaper commented on Feb 15, 2026

    @Dreamescaper

    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)

  16. ajcvickers commented on Feb 16, 2026

    @ajcvickers
    ContributorAuthor

    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.

  17. wertzui commented on Feb 18, 2026

    @wertzui
    Contributor

    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.

  18. mguinness commented on Feb 25, 2026

    @mguinness

    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:

    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?

    migrationBuilder.CreateTable(
        name: "Favorites",
        columns: table => new
        {
            EntityId = table.Column<int>(type: "int", nullable: false),
            EntityType = table.Column<string>(type: "nvarchar(50)", nullable: false),
            UserId = table.Column<int>(type: "int", nullable: false)
        },
        constraints: table =>
        {
            table.PrimaryKey("PK_Favorites", x => new { x.EntityId, x.EntityType, x.UserId });
    
            //Redundant FK
            table.ForeignKey(
                name: "FK_Favorites_Blogs_EntityId",
                column: x => x.EntityId,
                principalTable: "Blogs",
                principalColumn: "Id",
                onDelete: ReferentialAction.Cascade);
        });
    
    //Redundant index
    migrationBuilder.CreateIndex(
        name: "IX_Favorites_EntityId",
        table: "Favorites",
        column: "EntityId",
        unique: true);
  19. added a commit that references this issue on Jun 9, 2026
    9e0d72e
  20. modified the milestones: Backlog, 11.0.0 on Jun 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions