【问题标题】:Make Foreign Key (string field) nullable使外键(字符串字段)可以为空
【发布时间】:2015-04-08 09:40:33
【问题描述】:

我的模型是这样的

 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]),

谁能指出实现这一目标的正确方法?

注意:我使用的是实体框架代码优先方法

【问题讨论】:

  • 也许这会回答你的问题stackoverflow.com/questions/2366854/…
  • 这是什么版本的EF?顺便说一句,您可以使用 DbMigration 类中的 Up 方法将自己的逻辑用于模式生成。

标签: c# asp.net-mvc entity-framework ef-code-first


【解决方案1】:

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

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

检查此link 并转到“一对多关系的可空外键。”部分。

【讨论】:

  • 这会引发编译时错误 错误 1 ​​类型“字符串”必须是不可为空的值类型才能将其用作泛型类型或方法“System.Nullable”中的参数“T” T>' App\Models\Appointment.cs 104 24 DiagnosisApp
  • 是的,字符串是引用类型,所以你不需要将该属性声明为可为空,只需配置即可。
  • HasOptional 不存在于EntityTypeBuilder... ef core 5.0.12
【解决方案2】:

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

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

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-11
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    相关资源
    最近更新 更多