Muzingaye
Muzingaye

Reputation: 205

The Insert statement conflict with the FOREIGN KEY constraint. Entity Framework

my models are as follows...

public class Company
{


    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

    [Required]
    [MaxLength(50)]
    public string Name { get; set; }

    [Required]
    [MaxLength(255)]
    public string Fullname { get; set; }

    public bool HasFuneralInsuranceParlours { get; set; }
    public bool HasFuneralInsurancePolicies { get; set; }
    public bool HasLifeInsurancePolicies { get; set; }


    public bool IsDeleted { get; set; }

    public virtual List<Office> Offices { get; set; }
}


public class Office
{

   [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

    [MaxLength(50)]
    public string Name { get; set; }

    [MaxLength(100)]
    public string Address1 { get; set; }

    [MaxLength(100)]
    public string Address2 { get; set; }

    [MaxLength(100)]
    public string Address3 { get; set; }

    [MaxLength(20)]
    public string Telephone { get; set; }

    [MaxLength(20)]
    public string Fax { get; set; }

    [MaxLength(255)]
    public string Email { get; set; }

    public bool IsDeleted { get; set; }

    public Guid CompanyId { get; set; }
    public virtual Company Companies { get; set; }

    public virtual List<Employee> Employees { get; set; }

}

and controllers

 [HttpPost]
 [ValidateAntiForgeryToken]
 public ActionResult Create(OfficeModel model)
    {

        bool success = false;
        string message = "";
        byte[] logo = null;

        var user = SecurityHelper.GetAuthenticatedUser(this.HttpContext);
        try
        {

            if (ModelState.IsValid)
            {
                if (model.Name.IsNullOrWhitespace()) throw new Exception("Unable to create this Employee Name. The Type cannot be blank or spaces.");
                if (models.Offices.Any(x => x.Name.ToLower() == model.Name.ToLower())) throw new Exception(string.Format("This Office's Name '{0}' already exists. Please check your data.", model.Name.ToUpperCase()));


                var entry = new Office
                {
                    Id  = Guid.NewGuid(),
                    Name = model.Name.ToUpperCase(),
                    Address1 = model.Address1.ToUpperCase(),
                    Address2 = model.Address2.ToUpperCase(),
                    Address3 = model.Address3.ToUpperCase(),
                    Telephone = model.Telephone.ToUpperCase(),
                    Fax = model.Fax.ToUpperCase(),
                    Email = model.Email.ToUpperCase(),
                    IsDeleted = false,
                    CompanyId = user.CompanyId,

                    Bankings =  new List<Banking>()
                    {
                        new Banking
                        {
                            Bank = model.OfficeBank.ToUpperCase(),
                            Account = model.BankAccount.ToUpperCase(),
                            Branch = model.Branch.ToUpperCase(),
                            BranchNo = model.BranchNo.ToUpperCase(),
                            AccountType = model.AccountType.ToUpperCase()
                        }
                    }
                };
                models.Offices.Add(entity);
                success = true;
                return RedirectToAction("Index");
            }
            else
            {
                message = "An error was cought please check your data and retry";
            }
        }
        catch (Exception ex)
        {
            message = ex.Message;
        }

        return View(model);
    }

when l debug the above code l return the following error

"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_dbo.Offices_dbo.Companies_CompanyId\". The conflict occurred in database \"PolicyManager\", table \"dbo.Companies\", column 'Id'.\r\nThe statement has been terminated."

When l hover model.Name l am return a value but the rest return me a null value which l suspect the thus the cause of the the above error.

What problem can it possible be because l have used the similar code before and it worked. May anyone help. Thank you in advance

Upvotes: 4

Views: 12417

Answers (1)

Shiraz Bhaiji
Shiraz Bhaiji

Reputation: 65461

You are adding a New Office.

The error says that there is a referential integrity problem With the Foreign key constraint to the Company table.

When you create the Order you add the following Company key:

CompanyId = user.CompanyId

So it appears that user.CompanyId is not an id that is registered against an existing Company.

Upvotes: 5

Related Questions