Home > other >  EF Core : how to add items into Navigation Property with one-to-many relationship?
EF Core : how to add items into Navigation Property with one-to-many relationship?

Time:10-13

I'm trying to add stuff into the navigation property.

I want to build a system that allows an user to enter records into the database. A record has at least one or more permits. Therefore, it has a one-to-many relationship.

I was trying to input one job nature with a permit, but I get this error:

Object reference not set to an instance of an object

How do I pass items from the Permit class into the main record class?

Classes

[Table("record" , Schema = "public")]
public class Record
{
    [Key]
    public string Serial_Num {get; set;}
    public string job_nature {get; set;}
    //navigation property
    public ICollection<Permit> permits {get; set;}
}

[Table("permit" , Schema = "public")]
public class Permit
{
    [Key]
    public int id {get; set;}
    public string Serial_Num {get; set;}
    public string permit {get; set;}
    //navigation property
    [Required]
    public Record Record {get; set;}
}

Model builder

modelBuilder.Entity<Record>()
                .HasMany(p => p.permits)
                .WithOne(r => r.Record)
                .HasForeignKey(p => p.Serial_Num)
                .OnDelete(DeleteBehavior.Cascade);

Part of the code (1-to-1 relationship trial)

// Record Class
Record objRecord = new Record();
objRecord.Serial_Num = "001";
objRecord.job_nature = "test";

// Permit Class
Permit objPermit = new Permit();
objPermit.Serial_Num = objRecord.Serial_Num;
objPermit.permit = "permit_test";

// I'm trying to include Permit into Record, but returns 'Object reference not set to an instance of an object' error.
objRecord.permits.Add(objPermit);
context.record.Add(objRecord);
context.SaveChanges();

CodePudding user response:

[Table("record" , Schema = "public")]
public class Record
{
    // Add the constructor to initialize permits
    public Record()
    {
        permits = new HashSet<Permit>();
    }
    
    [Key]
    public string Serial_Num {get; set;}
    public string job_nature {get; set;}
    //navigation property
    public ICollection<Permit> permits {get; set;}
}

CodePudding user response:

How about this:

objRecord.permits = new List<Permit>()

And then add to the list.

  • Related