Skip to content

Constants in composite foreign keys #25141

Closed as duplicate
Closed as duplicate

Description

@hauntingEcho

What problem are you trying to solve?

I've recently inherited a codebase which makes heavy use of the pattern:

class Address {
  int AddressID;
  int RefType;
  int RefID;
  string Address;
}
class Customer {
  int CustomerID;
}
class Contact {
  int ContactID;
}
enum RefType {
  Customer = 1,
  Contact = 2,
  User = 3,
  // ...
}

I'd like to add a link from the Customer to their Address, meaning that the expected pattern would be to either:

  • use a discriminator. They're already using context.Addresses pretty heavily across multiple repos, so this would break everywhere that they're manually setting RefType as well as breaking for undocumented values of RefType that crop up. The changes to discriminator behavior needed to make this work seem like they'd be a much bigger request to make.
  • use something like the following:
entity
  .HasOne(c => c.Address)
  .HasOne()
  .HasForeignKey<Address>(a => new { a.RefID, a.RefType })
  .HasPrincipalKey<Customer>(c => new { c.CustomerID, RT = (int)RefType.Customer });

related StackOverflow

Describe the solution you'd like

The ability to use a constant value for one or more properties in the composite forms of HasForeignKey and HasPrincipalKey

Activity

  1. AndriySvyryd commented on Jun 25, 2021

    @AndriySvyryd
    Member

    This will be possible when #7623 is implemented.

  2. angelaki commented on Feb 19, 2025

    @angelaki

    @ajcvickers, @AndriySvyryd or anyone else, just to make sure, is this still correct for EFCore 9.0? I'm having a quite simple use-case I tought:

    I'm having a table to store key/value pairs for any objects (string Module, Guid Id, string Name, string Value). Now I tought I'd be able to make the relations this way:

    a.HasMany(p => p.Tags).WithOne().HasPrincipalKey(p => new { Module = Module.Name, p.Id }).HasForeignKey(p => new { p.Module, p.Id }); but EFCore brings an System.ArgumentException because of the constant value.

    Ok, I could say Guids won't overlap anyway but I'd rather have a clean join here.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions