我如何 link 两个属性到一个 class 但只能引用 EFC Code First 中的一个属性?

How do I link two properties to one class but only being able to reference to one in EFC Code First?

我有两个 类:

public class User
{
    public Guid UserId { get; set; }
    [Required]
    public string Username { get; set; }
    [Required]
    public string Password { get; set; }

    public UserProfile UserProfile { get; set; }
}

public class UserProfile
{
    public int UserProfileId { get; set; }
    public string Avatar { get; set; }

    public User User { get; set; }
    public User Wingman { get; set; }
}

尝试以可理解的方式添加迁移时出现以下错误:

Unable to determine the relationship represented by navigation property 'User.UserProfile' of type 'UserProfile'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

UserProfile.User 是用户本身,UserProfile.Wingman 是代表僚机的另一个用户。 我需要另一个 Table 来解决这个问题吗?还是有其他方法可以解决这个问题? 而且我不需要从 User.

中引用 Wingman

提前致谢!

您可以使用 InversePropertyAttribute 或 Fluent API 配置方法 HasOne/WithOneHasOne/WithMany 以及适当的 属性 选择器。

如果您正在寻找 1:1 关系,请使用分片主键 - 将 UserProfile 的 PK 设为用户的 FK。

modelBuilder.Entity<UserProfile>()
    .HasOne( up => up.User )
    .WithOne( u => u.UserProfile )
    .HasForeignKey( up => up.UserProfileId ); // I suggest renaming PK to UserId for clarity

如果有1:N关系,两种方式;首先,带 InversePropertyAttribute:

public class User
{
    ...
    [InverseProperty( "User" )]
    public ICollection<UserProfile> UserProfiles { get; set; }
}

或通过 Fluent API:

modelBuilder.Entity<UserProfile>()
    .HasOne( up => up.User )
    .WithMany( u => u.UserProfiles );