Home > database >  Can not create an optional/nullable foreign key
Can not create an optional/nullable foreign key

Time:02-10

I have 2 models

public class Battle
    {
        public int Id { get; set; }
        public Event Event { get; set; }
        public int EventId { get; set; }
    }

public class Event 
    {
        public int Id { get; set; }
        public List<Battle> Battles { get; set; }
    }

I want to make EventId in the Battles table an optional foreign key.

I have tried several ways but non of them worked, FE:

            modelBuilder.Entity<Battle>()
                .HasOne(e => e.Event)
                .WithMany(e => e.Battles)
                .IsRequired(false);

or

public class Battle
    {
        public int Id { get; set; }
        public Event? Event { get; set; }
        public int? EventId { get; set; }
    }

CodePudding user response:

Well, I made a mistake, I was setting a 0 value to the EventId but it should be null or any int number > 0.

  • Related