Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将两个属性链接到一个类,但只能首先在EFC代码中引用一个?_C#_Asp.net Core_Ef Code First_Entity Framework Core - Fatal编程技术网

C# 如何将两个属性链接到一个类,但只能首先在EFC代码中引用一个?

C# 如何将两个属性链接到一个类,但只能首先在EFC代码中引用一个?,c#,asp.net-core,ef-code-first,entity-framework-core,C#,Asp.net Core,Ef Code First,Entity Framework Core,我有两门课: 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 UserProf

我有两门课:

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; }
}
尝试添加迁移时出现以下错误,这是可以理解的:

无法确定导航所表示的关系 类型为“UserProfile”的属性“User.UserProfile”。要么手动 配置关系,或使用忽略此属性 “[NotMapped]”属性,或使用中的“EntityTypeBuilder.Ignore” “OnModelCreating”

UserProfile.User
是用户本身,而
UserProfile.Wingman
是另一个代表Wingman的用户。 我需要另一张桌子吗,比如一座桥,还是有其他方法来解决这个问题? 我不需要从
用户
中引用
僚机

提前谢谢

您可以使用或Fluent API配置方法
HasOne
/
with one
HasOne/with many
以及适当的属性选择器

如果您正在寻找1:1的关系,请使用shard主键-将UserProfile的PK设置为FK to User

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

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