none
Entity Framework: How EF will add value automatically for FK field RRS feed

  • Question

  • my entity relation is like Customer > Address > Contacts. each customer may have multiple addresses and each address may have multiple contacts.

    my Entity POCO classes as like

    public class CustomerBase
    {
        public int CustomerID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    
        [NotMapped]
        public string Address1 { get; set; }
    
        [NotMapped]
        public string Address2 { get; set; }
    
        [NotMapped]
        public string Phone { get; set; }
    
        [NotMapped]
        public string Fax { get; set; }
    
    }
    
    public class Customer : CustomerBase
    {
        public virtual List<Addresses> Addresses { get; set; }
    }
    
    public class Addresses
    {
        [Key]
        public int AddressID { get; set; }
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public bool IsDefault { get; set; }
        public int SerialNo { get; set; }
        public virtual List<Contacts> Contacts { get; set; }
    
        public int CustomerID { get; set; }
        //[ForeignKey("CustomerID")]
        public virtual Customer Customer { get; set; }
    }
    
    public class Contacts
    {
        [Key]
        public int ContactID { get; set; }
    
        public string Phone { get; set; }
        public string Fax { get; set; }
        public bool IsDefault { get; set; }
        public int SerialNo { get; set; }
        public int AddressID { get; set; }
    
        //[ForeignKey("AddressID")]
        public virtual Addresses Customer { get; set; } 
    
    }

    My DB context look like

    public class TestDBContext : DbContext
    {
        public TestDBContext()
            : base("name=TestDBContext")
        {
            //((IObjectContextAdapter)this).ObjectContext.SavingChanges += new EventHandler(objContext_SavingChanges);
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //modelBuilder.Configurations.Add(new vwCustomerConfiguration());
            Database.SetInitializer<TestDBContext>(null);
        }
    
        public DbSet<Customer> Customer { get; set; }
        public DbSet<Addresses> Addresses { get; set; }
        public DbSet<Contacts> Contacts { get; set; }
        public virtual DbSet<vwCustomer> vwCustomers { get; set; }
        public DbSet<vwMyCustomers> vwMyCustomers { get; set; }
    }

    Now here is code which is update parent and insert new child data into address and contact table.

        using (var db = new TestDBContext())
        {
            //db.Database.Log = s => MyLogger.Log("EFApp", s);
    
            var existingCustomer = db.Customer
            .Include(a => a.Addresses.Select(x => x.Contacts))
            .FirstOrDefault(p => p.CustomerID == 5);
    
            existingCustomer.FirstName = "New Customer";
    
            existingCustomer.Addresses.Where(a => a.AddressID == 5).ToList().ForEach(r => db.Addresses.Remove(r));
            existingCustomer.Addresses.Where(a => a.AddressID == 5).SelectMany(ad => ad.Contacts).Where(c=> c.ContactID==5).ToList().ForEach(r => db.Contacts.Remove(r));
    
            Addresses oAdrModel = new Addresses();
            oAdrModel.Address1 = "New test xxx";
            oAdrModel.Address2 = "New test xxx";
            oAdrModel.SerialNo = 3;
            oAdrModel.IsDefault = true;
            //oAdrModel.CustomerID = 5;
            existingCustomer.Addresses.Add(oAdrModel);
            //db.Addresses.Add(oAdrModel);
            //db.SaveChanges();
            //int CurAddressID = oAdrModel.AddressID;
    
            Contacts ContactModel = new Contacts();
            ContactModel.Phone = "New XX-1111111-33";
            ContactModel.Fax = "New XX-1-1111111";
            ContactModel.SerialNo = 4;
            ContactModel.IsDefault = true;
            oAdrModel.Contacts.Add(ContactModel);
    
            //ContactModel.AddressID = CurAddressID;
            //db.Contacts.Add(ContactModel);
    
            db.SaveChanges();
        }

    oAdrModel.Contacts.Add(ContactModel); throwing error called Object reference not set to an instance of an object. just do not understand what was the fault in code.

    Monday, November 7, 2016 9:56 AM

Answers

  • full working code

                using (var db = new TestDBContext())
                {
                    //db.Database.Log = s => MyLogger.Log("EFApp", s);
    
                    var existingCustomer = db.Customer
                    .Include(a => a.Addresses.Select(x => x.Contacts))
                    .FirstOrDefault(p => p.CustomerID == 5);
    
                    existingCustomer.FirstName = "New Customer";
    
                    existingCustomer.Addresses.Where(a => a.AddressID == 5).ToList().ForEach(r => db.Addresses.Remove(r));
                    existingCustomer.Addresses.Where(a => a.AddressID == 5).SelectMany(ad => ad.Contacts).Where(c=> c.ContactID==5).ToList().ForEach(r => db.Contacts.Remove(r));
    
                    Addresses oAdrModel = new Addresses();
                    oAdrModel.Address1 = "New test xxx";
                    oAdrModel.Address2 = "New test xxx";
                    oAdrModel.SerialNo = 3;
                    oAdrModel.IsDefault = true;
                    //oAdrModel.CustomerID = 5;
                    existingCustomer.Addresses.Add(oAdrModel);
                    //db.Addresses.Add(oAdrModel);
                    //db.SaveChanges();
                    //int CurAddressID = oAdrModel.AddressID;
    
                    oAdrModel.Contacts = new List<Contacts>();
                    Contacts ContactModel = new Contacts();
                    ContactModel.Phone = "New XX-1111111-33";
                    ContactModel.Fax = "New XX-1-1111111";
                    ContactModel.SerialNo = 4;
                    ContactModel.IsDefault = true;
                    //ContactModel.Addresses = oAdrModel;
                    oAdrModel.Contacts.Add(ContactModel);
    
                    //ContactModel.AddressID = CurAddressID;
                    //db.Contacts.Add(ContactModel);
    
                    db.SaveChanges();
                }

    if i add this line oAdrModel.Contacts = new List<Contacts>(); then no null object ref error is occurring but why i need to add this line oAdrModel.Contacts = new List<Contacts>(); ?

    but in case of address i do not have to write this sort of line of code and this line is working fine existingCustomer.Addresses.Add(oAdrModel);

    please some one explain me. thanks

    • Marked as answer by Sudip_inn Monday, November 7, 2016 11:31 AM
    Monday, November 7, 2016 10:24 AM