0

I'm using ASP.NET Identity in my project so my AspNetUser table looks somewhat like this:

public class AspNetUser
{
    [Key, Index(IsUnique = true), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

    [Index(IsUnique = true), DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int InternalId { get; set; }

    // Navigation properties
    public virtual ICollection<RequestHistory> RequestHistories { get; set; }
}

I've added InternalId to use as foreign key in my custom tables because i don't like using Guids everywhere. So, let's take this table for example:

public class RequestHistory
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public int? UserId { get; set; }

    // Navigation properties
    [ForeignKey("UserId")]
    public virtual AspNetUser User { get; set; }
}

Looks good so far, RequestHistory should have navigation property to AspNetUser running on RequestHistory.UserId = AspNetUser.InternalId and vice versa. But when i try to run my project i get an error saying:

RequestHistory_User_Target_RequestHistory_User_Source: : The types of all properties in the Dependent Role of a referential constraint must be the same as the corresponding property types in the Principal Role. The type of property 'UserId' on entity 'RequestHistory' does not match the type of property 'Id' on entity 'AspNetUser' in the referential constraint 'RequestHistory_User'.

Which makes sense because EF is propably trying to match them using the default behaviour but how can i force this association to use InternalId as foreign key from AspNetUser table?

Frag
  • 11
  • 3
  • Please check the below question on Stack Overflow http://stackoverflow.com/questions/27609023/how-to-get-ef6-to-honor-unique-constraint-on-fk-in-association-relationship-mu – AzizKap21 May 05 '16 at 22:49
  • Thank you for you answer, but are you implying that it cannot be done because `The Entity Framework currently only supports basing referential constraints on primary keys`? – Frag May 06 '16 at 06:59

1 Answers1

0

You need to set foreign key to InternalId instead of UserId on RequestHistory.

User123
  • 549
  • 1
  • 11
  • 24
  • I wish it would be this easy. ForeignKey attributes relates to the same class, so by specifiying ForeignKey on User object all im doing is telling EF to put the actualy key inside UserId property. But to double check i've changed ForeignKey to InternalId and as expected i get `The ForeignKeyAttribute on property 'User' on type 'RequestHistory' is not valid. The foreign key name 'InternalId' was not found on the dependent type 'RequestHistory'. The Name value should be a comma separated list of foreign key property names.` – Frag May 06 '16 at 07:02