Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Foreign Key (string field) nullable

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

like image 951
None Avatar asked Dec 12 '22 00:12

None


1 Answers

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."

like image 63
octavioccl Avatar answered Dec 29 '22 12:12

octavioccl