1

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!

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Sivvie Lim
  • 784
  • 2
  • 14
  • 43
  • 1
    `Pets` is null until you assign something to it with, eg `newOwner.Pets=new List();` or . EF isn't used at all until `context.PetOwners.Add(newOwner);` – Panagiotis Kanavos Jun 06 '19 at 08:52
  • 1
    The code has another serious bug - defining the context as `static DataContext context`. Contexts are like connections, they should be short-lived and closed as soon as they are no longer needed. Instead of a static field, there should be a `using(var context=new DataContext){...}` block in the method that actually needs to store data. Instead of calling `SaveChanges` for every single operation, all operations that belong together should be performed on the same context, with `SaveChanges` called only in the last step. – Panagiotis Kanavos Jun 06 '19 at 08:54
  • Using a DbContext properly means there's no need for an open connection or even a transaction until `SaveChanges` is called. SaveChanges uses a transaction internally, so saving multiple changes is atomic. If you don't want those changes, just don't call `SaveChanges` – Panagiotis Kanavos Jun 06 '19 at 08:57
  • @PanagiotisKanavos got it, thanks! – Sivvie Lim Jun 06 '19 at 09:31

0 Answers0