I am new to the Entity Framework and I've been trying to establish a one-to-many relationship between two class which is Pet and PetOwner, one PetOwner can have many pets.
The database was migrated successfully using code-first approach. However, the insertion of data is not. I keep getting this null object reference error when I try to add pets into petowner list of pets.
I have tried googling many places and even redo the project a few times but still couldn't get it. I think I was missing out something.
Below is my code:
Property Class
public class Pet
{
public int PetID { get; set; }
public string PetName { get; set; }
public string PetSpecies { get; set; }
public int PetOwnerID { get; set; }
public PetOwner PetOwner { get; set; }
}
public class PetOwner
{
public int PetOwnerID { get; set; }
public string PetOwnerName { get; set; }
public string Gender { get; set; }
public ICollection<Pet> Pets { get; set; }
}
Data Context Model
class DataContext : DbContext
{
public DataContext() : base("Pet") { }
public DbSet<Pet> Pets { get; set; }
public DbSet<PetOwner> PetOwners { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//One-To-Many Relationship
modelBuilder.Entity<Pet>()
.HasRequired<PetOwner>(p => p.PetOwner)
.WithMany(p => p.Pets)
.HasForeignKey<int>(p => p.PetOwnerID);
}
}
Insert Data
public class PetOperation
{
static DataContext context = new DataContext();
public static void Insert()
{
try
{
var newPet = new Pet();
newPet.PetName = "Larry";
newPet.PetSpecies = "Snake";
var newOwner = new PetOwner();
newOwner.PetOwnerName = "Kiki";
newOwner.Gender = "Female";
newPet.PetOwnerID = newOwner.PetOwnerID;
newPet.PetOwner = newOwner;
newOwner.Pets.Add(newPet);
context.PetOwners.Add(newOwner);
context.Pets.Add(newPet);
context.SaveChanges();
Console.WriteLine("Success!");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex}");
}
}
}
The error is occured in this line: newOwner.Pets.Add(newPet);
Hope anyone could help me with this. Thank you!