如何定义应该使用哪个外键导航属性?

How to define which foreign key navigation property should use?

我有两个模型类

注册

public class Registration
{
    // PK
    public int Id { get; private set; }
    
    // FK's
    public string AspNetUsersId { get; private set; }
    public int TimetableId { get; private set; }

    // EF Navigation properties
    public Timetable Timetable { get; set; }
    public ApplicationUser ApplicationUser { get; set; }

    // EF ctor
    private Registration()
    {
    }

    // public ctor
    public Registration(string aspNetUsersId, int timetableId)
    {
        AspNetUsersId = aspNetUsersId;
        TimetableId = timetableId;
    }
}

应用程序用户

public class ApplicationUser : IdentityUser
{
   // some not relevant columns
}

当我尝试执行这段代码时

var registrationExists = _context.Registrations
     .Where(x => x.AspNetUsersId == user.Id 
          && x.TimetableId == timetable.Id)
     .SingleOrDefault();

我收到一个错误

Microsoft.Data.SqlClient.SqlException: 'Invalid column name 'ApplicationUserId'.

我认为这是因为 EF 正试图(根据默认约定)在数据库中查找 Registration.ApplicationUserId 列,因为 ApplicationUser 导航 属性。但是 属性(和 sql 列)被命名为 AspNetUsersId 而不是 ApplicationUserId。如何在模型构建器 (dbContext) 中覆盖此命名?

我试过

modelBuilder.Entity<Registration>(b => 
{
    b.HasAlternateKey(x => x.AspNetUsersId);
    b.HasOne(n => n.ApplicationUser); 
});

可是我没图,怎么配图呢

您可以在字段上写注释,例如

// PK
[Key]
public int Id { get; private set; }
    
// FK's
[ForeignKey(nameof(AspNetUsersId))]
public string AspNetUsersId { get; private set; }
[ForeignKey(nameof(TimetableId ))]
public int TimetableId { get; private set; }

现在,属性 [key] 是主键,带有 [ForeignKey()] 的属性是外键。

您还可以使用模型构建器:

modelBuilder.Entity<Registration>( 
  .HasAlternateKey(x => x.AspNetUsersId)
  .HasOne(n => n.ApplicationUser)
  .WithMany()
  .HasForeignKey(f => f.AspNetUsersId);

https://docs.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key#single-navigation-property-1)

https://entityframeworkcore.com/model-relationships