Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Constants in composite foreign keys #25141

Closed
hauntingEcho opened this issue Jun 23, 2021 · 2 comments
Closed

Constants in composite foreign keys #25141

hauntingEcho opened this issue Jun 23, 2021 · 2 comments

Comments

@hauntingEcho
Copy link

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

@AndriySvyryd
Copy link
Member

This will be possible when #7623 is implemented.

@angelaki
Copy link

@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
Projects
None yet
Development

No branches or pull requests

4 participants