4

My model is like this

 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; }
}

I expect ApplicationUserId to be nullable Foreign Key , But it is not created like that on table

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

Can anyone point out correct approach to achieve this?

Note: I am using Entity framework code first approach

None
  • 5,582
  • 21
  • 85
  • 170
  • Maybe this will answer your question http://stackoverflow.com/questions/2366854/can-table-columns-with-a-foreign-key-be-null – Diizzy Apr 08 '15 at 12:09
  • What version of EF is this? BTW you can put your own logic for schema generation stuff by using Up method from DbMigration class. – E-Bat Apr 08 '15 at 14:44

2 Answers2

8

By your model, I guess you are trying to create an one-to-many relationship between ApplicationUser and Appointment (one user could have more than one Appointment). If that is the case, you could configure that relationship in the OnModelCreating method on your context this way:

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

Check this link and go to the section "Nullable foreign key for one-to-many relationship."

ocuenca
  • 38,548
  • 11
  • 89
  • 102
  • This throws a compile time error Error 1 The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable' App\Models\Appointment.cs 104 24 DiagnosisApp – None Apr 08 '15 at 12:39
  • it's true, string is a reference type, so you don't need to declare that property as nullable, try just with the configuration. – ocuenca Apr 08 '15 at 12:44
  • `HasOptional` doesn't exist on `EntityTypeBuilder`... ef core 5.0.12 – Matthias Burger Dec 01 '21 at 16:34
5

For EF core, you can write below codes in OnModelCreating :

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

    }
Bora Aydın
  • 439
  • 4
  • 6