0

I'm getting a "Cannot insert null into column" error from an unrelated table when trying to add a new record for the "original" table.

I have the following two (relevant) entities:

public class Complex
{
    [Key]
    public Guid Id { get; set; }
    public string Name { get; set; }

    public Guid OwnerId { get; set; }
    [ForeignKey("OwnerId")]
    public Owner Owner { get; set; }

    public Guid AddressId { get; set; }
    [ForeignKey("AddressId")]
    public virtual Address Address { get; set; }

    public virtual ICollection<Unit> Units { get; set; }
    public virtual ICollection<StaffMember> StaffMembers { get; set; }

    public Complex()
    {
        this.Id = System.Guid.NewGuid();
        this.Units = new HashSet<Unit>();
        this.StaffMembers = new HashSet<StaffMember>();
    }

    public void AddUnit(Unit unit)
    {
        Units.Add(unit);
    }

    public void AddStaff(StaffMember staffMember)
    {
        StaffMembers.Add(staffMember);
    }
}

and

public class Owner
{
    [Key]
    public Guid Id { get; set; }
    public string Name { get; set; }
    public Guid ContactInfoId { get; set; }
    [ForeignKey("ContactInfoId")]
    public ContactInfo ContactInfo { get; set; }

    public ICollection<StaffMember> Employees { get; set; }
    public ICollection<Complex> Complexes { get; set; }

    public Owner()
    {
        this.Id = System.Guid.NewGuid();
        this.Employees = new HashSet<StaffMember>();
        this.Complexes = new HashSet<Complex>();
    }

    public void AddEmployee(StaffMember employee)
    {
        Employees.Add(employee);
    }

    public void AddComplex(Complex complex)
    {
        Complexes.Add(complex);
    }
}

I'm trying to add a new owner in the following code:

if (ModelState.IsValid)
        {
            Owner newOwner = new Owner();
            ContactInfo newContactInfo = new ContactInfo();
            Address newAddress = new Address();

            newAddress.Address1 = viewModel.ContactInfo.Address.Address1;
            newAddress.Address2 = viewModel.ContactInfo.Address.Address2;
            newAddress.City = viewModel.ContactInfo.Address.City;
            newAddress.State = viewModel.ContactInfo.Address.State;
            newAddress.Zip = viewModel.ContactInfo.Address.Zip;

            newContactInfo.Address = newAddress;
            newContactInfo.Email = viewModel.ContactInfo.Email;
            newContactInfo.Phone1 = viewModel.ContactInfo.Phone1;
            newContactInfo.Phone2 = viewModel.ContactInfo.Phone2;

            newOwner.Name = viewModel.Name;
            newOwner.ContactInfo = newContactInfo;

            using (REMSDAL dal = new REMSDAL())
            {
                dal.Owners.Add(newOwner);

                var result = await dal.SaveChangesAsync();

                if (result > 0)
                {
                    viewModel.ActionStatusMessageViewModel.StatusMessage = "Owner " + viewModel.Name + " added.";
                    viewModel.Name = "";

                    return View(viewModel);
                }
            }
        }

...but getting this error:

Exception Details: System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'OwnerId', table 'REMS.dbo.Complexes'; column does not allow nulls. UPDATE fails. The statement has been terminated.

How can I be getting an error regarding Complexes when I'm trying to add an Owner?

Chris V.
  • 1,123
  • 5
  • 22
  • 50
  • The owner class has a property called Complexes (defined as a collection), and that's the relationship that causes the update in the other table. – Sparrow Aug 29 '17 at 17:32
  • So what do I need to change to allow the complexes collection to be empty? I would like an owner entity to have no complexes under it. It's already initialized in the constructor to have an empty collection. – Chris V. Aug 29 '17 at 17:34
  • There are several ways to exclude a property from update. For example, using the mapping (ignore). See this post as an example: https://stackoverflow.com/questions/20353665/ignore-one-property-on-update-entity-framework – Sparrow Aug 29 '17 at 17:38
  • You could also see this one for another method: https://stackoverflow.com/questions/12661881/exclude-property-on-update-in-entity-framework – Sparrow Aug 29 '17 at 17:38
  • So in my situation I would use something like: void CreateOwner() { var owner= new Owner(); ...new owner details... Mapper.CreateMap() .ForMember(dest => dest.Complexes, opt => opt.Ignore()); db.SaveChanges(); } Correct? Also, this will only restrict updates on that property in this context, correct? – Chris V. Aug 29 '17 at 17:43
  • or in the case of your second example: db.Entry(model).State = EntityState.Modified; db.Entry(model).Property(x => x.Complexes).IsModified = false; db.SaveChanges(); Though I'm not sure what "model" represents here. – Chris V. Aug 29 '17 at 17:46
  • Also apparently the record *is* being added to the DB, despite failing in the code. Perhaps I can just suppress the error with a try/catch? – Chris V. Aug 29 '17 at 18:17
  • using the try/catch is not the right solution. Model in the second example, is really the class that is mapped to the table (in your case it is owner class). Try the first solution. I think it will work for you. – Sparrow Aug 29 '17 at 19:05

0 Answers0