更新时间:2023-02-09 10:40:16
您好,
所有类都需要公开主键属性,因此您需要添加一个Profile.UserId属性。完成后,您可以按如下方式映射关系:
All classes need to expose a primary key property, so you would need to add a Profile.UserId property. Once you have done that you can map the relationship as follows:
public class ProfileContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Profile> Profiles { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Profile>()
.HasKey(p => p.UserId);
modelBuilder.Entity<User>()
.HasOptional(u => u.Profile)
.WithRequired()
.HasConstraint((u, p) => u.UserId == p.UserId);
}
}
public class User
{
public int UserId { get; set; }
public string Username { get; set; }
public Profile Profile { get; set; }
}
public class Profile
{
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string PostalCode { get; set; }
}