使外键(字符串字段)可为空

4
我的模型是这样的。
 public class Appointment
{
    public int AppointmentID { get; set; }
    public string AppointmentCode { get; set; }
    public string ApplicationUserId { get; set; }
    [ForeignKey("ApplicationUserId ")]
    public ApplicationUser ApplicationUser { get; set; }
    public int PriceId { get; set; }
}

我期望ApplicationUserId是可空的外键,但是在表中并没有这样创建。

  CONSTRAINT [FK_dbo.Appointment_dbo.IdentityUser_ApplicationUserId] FOREIGN KEY ([ApplicationUserId]) REFERENCES [dbo].[IdentityUser] ([Id]),

有人能指出正确的方法来实现这个吗?

注意:我正在使用Entity Framework的Code First方法。


也许这可以回答你的问题https://dev59.com/I3E95IYBdhLWcg3wUMLW - Diizzy
这是EF的哪个版本?顺便说一句,你可以使用DbMigration类中的Up方法来自己编写模式生成逻辑。 - E-Bat
2个回答

8

根据您的模型,我猜测您正在尝试创建ApplicationUserAppointment之间的一对多关系(一个用户可以有多个Appointment)。如果是这种情况,您可以在上下文中的OnModelCreating方法中按照以下方式配置该关系:

modelbuilder.Entity<Appoiment>().HasOptional(a=>a.ApplicationUser)
                                .WithMany(au=>au.Appointments)
                                .HasForeignKey(a=>ApplicationUserId);

请查看此链接,并前往"可空的一对多关系外键。"部分。


这会导致编译时错误 错误1:类型“string”必须是非可空值类型,才能在泛型类型或方法“System.Nullable<T>”中用作参数“T”。App\Models\Appointment.cs 104行24列 DiagnosisApp - None
没错,字符串是引用类型,所以您不需要将该属性声明为可空的,只需使用配置即可尝试。 - ocuenca
EntityTypeBuilder 上不存在 HasOptional... ef core 5.0.12。 - Matthias Burger

5

对于 EF Core,您可以在 OnModelCreating 中编写以下代码:

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Appoiment>().HasOne(a => a.ApplicationUser)
                .WithMany(au => au.Appointments)
                .HasForeignKey(a => a.ApplicationUserId)
                .IsRequired(false);

    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接