Base solution for your next web application
Open Closed

Code First - Non required field is required #2930


User avatar
0
rev319303 created

Can someone help please? I have entity Program that has two foreign keys to my subject table (MainContactSubjectId, SecondaryContactSubjectId). Both main and secondary are nullable longs. For some reason, when I try to insert entity Program it errors (Internal Server Error) and will not let me insert unless Main and Secondary are present. Below is my entity Program and some of my dbContext. Can anyone see what I am doing wrong?

namespace DiversionCore.AppTables.Programs
{
    [Table("Program")]
    public class Program : Entity<long>
    {

        [Required]
        public int TenantId { get; set; }

        [Required]
        public long ProgramTypeId { get; set; }

        [Required]
        [MaxLength(4000)]
        public string ProgramName { get; set; }

        public long? MainContactSubjectId { get; set; }

	public long? SecondaryContactSubjectId { get; set; }

        public virtual AppTables.ProgramTypes.ProgramType ProgramType { get; set; }
        public virtual AppTables.Subjects.Subject MainSubject { get; set; }
        public virtual AppTables.Subjects.Subject SecondarySubject { get; set; }
    }
}
//MY dBCONTEXT
//I'm guessing the problem is here but I'm not sure what it is. Without this code, the foreign keys are not getting created correctly and circular reference issues. 
			modelBuilder.Entity<AppTables.Programs.Program>()
					.HasRequired(m => m.MainSubject)
					.WithMany(t => t.ProgramsMain)
					.HasForeignKey(m => m.MainContactSubjectId)
					.WillCascadeOnDelete(false);

			modelBuilder.Entity<AppTables.Programs.Program>()
					.HasRequired(m => m.SecondarySubject)
					.WithMany(t => t.ProgramsSecondary)
					.HasForeignKey(m => m.SecondaryContactSubjectId)
					.WillCascadeOnDelete(false);

2 Answer(s)
  • User Avatar
    0
    rev319303 created

    I figured out my answer.

    I switched .HasRequired to .HasOptional and everything now works.

  • User Avatar
    0
    ismcagdas created
    Support Team

    Thanks rev319303 :)