Make foreign key (row field) null

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 it ApplicationUserIdto be NULL for the foreign key, but it is not created like in the table

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

Can someone point out the right approach to achieve this?

Note. I use the first approach for Entity infrastructure code.

+4
source share
2 answers

In your model, I think you're trying to create a one-to-many relationship between ApplicationUserand Appointment(one user can have more than one Appointment). If so, you can configure this relation in the method OnModelCreatingin your context as follows:

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

" " ".

+5

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

    }
0

All Articles