Insert 语句与 FOREIGN KEY 约束冲突。实体框架

Muz*_*ye 4 sql-server asp.net-mvc entity-framework

我的模型如下...

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; }

}
Run Code Online (Sandbox Code Playgroud)

和控制器

 [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);
    }
Run Code Online (Sandbox Code Playgroud)

当我调试上面的代码时,我返回以下错误

"INSERT 语句与 FOREIGN KEY 约束 \"FK_dbo.Offices_dbo.Companies_CompanyId\" 冲突。冲突发生在数据库 \"PolicyManager\"、表 \"dbo.Companies\"、列“Id”中。\r\n该语句已被终止。”

当我悬停 model.Name 时,我返回一个值,但其余的返回一个空值,我怀疑这是上述错误的原因。

这可能是什么问题,因为我之前使用过类似的代码并且它有效。愿任何人帮忙。先感谢您

Shi*_*iji 5

您正在添加一个新办公室。

该错误表明 Company 表的外键约束存在引用完整性问题。

创建订单时,您添加以下公司密钥:

CompanyId = user.CompanyId
Run Code Online (Sandbox Code Playgroud)

因此看来 user.CompanyId 不是针对现有公司注册的 ID。