【发布时间】:2015-01-03 16:26:30
【问题描述】:
我正在尝试创建一个友谊映射表,其中包含来自同一类(用户)的 2 个 FK。在添加迁移时,我收到以下错误:
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.
这是我的两个模型类。
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; }
}
我尝试覆盖 DbContext 中的 OnModelCreating 方法:
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);
}
这会导致显示新的错误消息。
Schema specified is not valid. Errors: The relationship 'GameAPI.Models.UserFriendMap_User' was not loaded because the type 'GameAPI.Models.User' is not available.
任何帮助将不胜感激。提前致谢!!
【问题讨论】:
-
这个问题的重复解决方案并没有真正达到同样的目的。我想将关系建模为数据库中的一个单独实体和一个单独的模型类,因为这种关系本身将超过友谊日期。
-
你是对的。而且,出乎意料的是,我找不到更好的副本。所以我决定深入研究一下,并添加了一个答案。
标签: c# entity-framework ef-code-first