AddRange - object reference not set to an instance of an object

tinac99 1 Reputation point
2021-09-06T05:12:31.403+00:00

Hi,

I'm running into "object reference not set to an instance of an object" error on the context.Addrange(varList) line. context is injected - scope.

public partial class CustomerContext : DbContext
{
    public CustomerContext()
    {
    }



    public CovidContext(DbContextOptions<CovidContext> options)
        : base(options)
    {
    }

    public virtual DbSet<Customer> Customer { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseNpgsql(connstring);
            optionsBuilder.EnableSensitiveDataLogging(true);

        }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasAnnotation("Relational:Collation", "English_United States.1252");

        modelBuilder.Entity<Customer>(entity =>
        {
            entity.HasKey(e => e.Id)
                .HasName("Customer_pkey");

            entity.ToTable("Customers");

            entity.Property(e => e.Id)
                .ValueGeneratedNever()
                .HasColumnName("Id");

            entity.Property(e => e.LastName).HasMaxLength(20);

            entity.Property(e => e.BirthDate).HasColumnType("date");

            entity.Property(e => e.FirstName).HasMaxLength(20);

            entity.Property(e => e.CreatedDate).HasColumnType("date");

        });

        OnModelCreatingPartial(modelBuilder);
    }

    partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}


public partial class Customer
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    public DateTime BirthDate { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public DateTime? CreatedDate { get; set; }
    public int? Count1 { get; set; }
    public int? Count2 { get; set; }
    public int? Count3 { get; set; }
}

public static class LoadUtilities
{
private static CustomerContext context;

    public static List<ObjectError> LoadData(string sfilepath, string soutput)
    {
        List<ObjectError> errList = new List<ObjectError>();
        ICollection<Customer> CustomerDataList = new List<Customer>();

        try
        {

            string[] lines = File.ReadAllLines(sfilepath, System.Text.Encoding.UTF7);
            string[] allCustomerDataString = lines.Where((source, index) => index != 0).ToArray();

            List<Customer> CustomerData = new List<Customer>();
                int ctr = 1;
                int numloops = (allCustomerDataString.Length - 2) / 1000;
                int remainder = 0;
                int quotient = Math.DivRem((allCustomerDataString.Length - 2), 1000, out remainder);
                if(remainder > 0) 
                    numloops++ ;


                for (int i = 0; i < numloops -1; i++)
                {
                    using (context)
                    {
                        CustomerData =
                        (from line in allCustomerDataString
                         where line.Split(',')[0].Length > 0 && line != ",,,,,,,"
                         select new Customer
                         {
                             Id = Convert.ToInt32(line.Split(',')[0]),  //Convert.ToInt32(sArrayCustomerData[0]),
                             BirthDate = Convert.ToDateTime(line.Split(',')[1]),
                             LastName = line.Split(',')[2],
                             FirstName = line.Split(',')[3],
                             CreatedDate = String.IsNullOrEmpty(line.Split(',')[4]) ? (DateTime?)null :  Convert.ToDateTime(line.Split(',')[4]),
                             Count1 = String.IsNullOrEmpty(line.Split(',')[5]) ? (int?)null : Convert.ToInt32(line.Split(',')[5]),
                             Count2 = String.IsNullOrEmpty(line.Split(',')[6]) ? (int?)null : Convert.ToInt32(line.Split(',')[6])
                             Count3 = String.IsNullOrEmpty(line.Split(',')[7]) ? (int?)null : Convert.ToInt32(line.Split(',')[7])

                             }).Take(1000).Skip(1000 * i).ToList();

                        try
                        {
                            context.Customers.AddRange(CustomerData);   //=> errors here
                            context.SaveChanges();
                        }
                        catch (Exception e)
                        {
                            //This either returns a error string, or null if it can’t handle that error
                            string smsg = e.Message;
                        }
                    }
                }

        }

        catch (Exception e)
        {
            ObjectError err = new ObjectError
            {
                ErrorMsg = e.Message,
                PrimaryKey = "-1"
            };

            errList.Add(err);

        }

        return errList;
    }
}

I appreciate your help!

Thanks,

tinac99

Developer technologies .NET Entity Framework Core
{count} votes

2 answers

Sort by: Most helpful
  1. Duane Arnold 3,216 Reputation points
    2021-09-06T10:38:17.33+00:00

    if you are talking about this context.Customers.AddRange(CustomerData), then CustomerData is a null value, an object in CustomerData is a null value or a property in an object in CustomerData is null value.

    Everything in .NET is an object "everything" even privative types, since it's an OO language. If an object is a null value, then it doesn't exist in memory. When code tries to address a null value object, then you are going to get the error message you are getting.

    You can set a debug breakpoint on the context line and use Quickwatch to look at the context of Customerdata, look at each object in the list and look at each object's properties until you find something that is null.

    https://devblogs.microsoft.com/devops/7-ways-to-look-at-the-values-of-variables-while-debugging-in-visual-studio/

    0 comments No comments

  2. tinac99 1 Reputation point
    2021-09-06T16:09:23.58+00:00

    Thanks for the reply. I looked at all the data(limited it to 20), and the items on the list and the properties were not null.

    System.NullReferenceException: 'Object reference not set to an instance of an object.'


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.