I'm trying to create a Friendship mapping table that has 2 FK's that originate from the same class (User). On Add-Migration I get the following error:
Unable to determine the principal end of an association between the types 'GameAPI.Models.UserFriendMap' and 'GameAPI.Models.User'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
Here are my two model classes.
public class User
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int UserID { get; set; }
[Required]
public string Username { get; set; }
public ICollection<UserFriendMap> Friendships { get; set; }
}
public class UserFriendMap
{
[Required]
[Key]
[Column(Order = 1)]
public int UserID { get; set; }
[Required]
[Key]
[Column(Order = 2)]
public int FriendID { get; set; }
[ForeignKey("UserID"), InversePropertyAttribute("Friendships")]
public User User { get; set; }
[ForeignKey("FriendID"), InversePropertyAttribute("Friendships")]
public User Friend { get; set; }
[Required]
public DateTime FriendshipDate { get; set; }
}
I tried override the OnModelCreating method in the DbContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<UserFriendMap>()
.HasKey(m => new { m.UserID, m.FriendID });
modelBuilder.Entity<UserFriendMap>()
.HasRequired(m => m.User)
.WithMany()
.HasForeignKey(m => m.UserID);
modelBuilder.Entity<UserFriendMap>()
.HasRequired(m => m.Friend)
.WithMany()
.HasForeignKey(m => m.FriendID);
}
This causes a new error message to be displayed.
Schema specified is not valid. Errors: The relationship 'GameAPI.Models.UserFriendMap_User' was not loaded because the type 'GameAPI.Models.User' is not available.
Any help would be greatly appreciated. Thanks in advance!!