1

Let's say I have a data model that looks like so:

dbo.Application
{
   int Id { get; set; }
   int ClientAlternateId { get; set; }
   ...

   public virtual Client Client { get; set; }
}

dbo.Client
{
   int Id { get; set; }
   int AlternateId { get; set; }
   string Name { get; set; }
   ...
}

Where the primary key on both tables is the Id column. the Application type is associated to the Client table via its AlternateId column (which is not a key). The data in this column is always unique.

Is there a way to get entity framework to map this? I don't believe I'll be able to use:

    HasRequired(t => t.Client).WithMany().HasForeignKey(c => c.ClientAlternateId);

since that field is not the primary key.

John
  • 17,163
  • 16
  • 65
  • 83
  • 2
    No. Associations always require primary keys. EF doesn't support associations with unique indexes (yet). – Gert Arnold Jan 28 '14 at 22:02
  • possible duplicate of [Create association on non-primary key fields with Entity Framework 4.1 Fluent API](http://stackoverflow.com/questions/7019052/create-association-on-non-primary-key-fields-with-entity-framework-4-1-fluent-ap) – Brian Jul 16 '14 at 16:36
  • Vote to add this as a new feature in Entity Framework http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/1050579-unique-constraint-i-e-candidate-key-support – Brian Jul 16 '14 at 16:41

1 Answers1

-1

When configuring the relationship in your AppDbContext you need to add .HasPrincipalKey() , this article might help
https://gavilan.blog/2019/04/14/entity-framework-core-foreign-key-linked-with-a-non-primary-key/

macleash
  • 102
  • 3