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 );