I have two Classes:
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; }
}
Trying to add a migration understandably i get the following error:
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
is the user itself and UserProfile.Wingman
is another user representig the wingman. Do i need another Table for that like a bridge or is there another way to resolve that problem? And I don't need to reference Wingman
from the User
.
Thanks in advance!
You can use the InversePropertyAttribute or the Fluent API config methods HasOne
/ WithOne
or HasOne/WithMany
with appropriate property selectors.
If you're looking for a 1:1 relationship, use a shard primary key - make the PK for UserProfile the 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
If 1:N relationship, two ways; first, w/ InversePropertyAttribute
:
public class User
{
...
[InverseProperty( "User" )]
public ICollection<UserProfile> UserProfiles { get; set; }
}
Or via Fluent API:
modelBuilder.Entity<UserProfile>()
.HasOne( up => up.User )
.WithMany( u => u.UserProfiles );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.