1

I am working with ASP.NET MVC and Entity Framework (code first).

I have all the entity tables that are created by default, and I want to create a Review table

public Guid Id { get; set; }
public ApplicationUser User { get; set; }
[MaxLength(125)]
[ForeignKey("User"),Column(Order = 0)]
public string ReviewerId { get; set; }
public DateTime Date{ get; set; }
[Required]
[MaxLength(125)]
public string Title{ get; set; }
public string Comment{ get; set; }
[ForeignKey("User"), Column(Order = 1)]
[MaxLength(125)]
public string ReviewedId { get; set; }     // who we are reviewing

However when I try to add this table using add-migration, I get this error:

The number of properties in the dependent and principal roles in a relationship constraint must be identical.

How do I solve this issue? My idea is , I would like to be able to search reviews either by ReviewedId or ReviewerId.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
dee dee
  • 33
  • 4
  • Sorry, I think this the better duplicate: https://stackoverflow.com/questions/5559043/entity-framework-code-first-two-foreign-keys-from-same-table – Christian Gollhardt Nov 04 '18 at 03:36

1 Answers1

1

The problem is that you have one navigation property to the user table:

public ApplicationUser User { get; set; }

but two foreign key properties that claim to be the foreign key of this one navigation property:

[ForeignKey("User"),Column(Order = 0)]
public string ReviewerId { get; set; }

[ForeignKey("User"), Column(Order = 1)]
public string ReviewedId { get; set; }

That's the actual mistake. EF trips over an inconsistent number of properties in the foreign key definition and the referred primary key and therefore doesn't get to the actual problem.

The fix is to define two navigation properies to ApplicationUser, for example:

[ForeignKey("Reviewer")]
public string ReviewerId { get; set; }
public ApplicationUser Reviewer{ get; set; }

[ForeignKey("ReviewedUser")]
public string ReviewedId { get; set; }
public ApplicationUser ReviewedUser{ get; set; }
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291