我的模型如下......
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; }
}
和控制器
[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);
}
当我调试上面的代码时,l返回以下错误
“INSERT语句与FOREIGN KEY约束冲突 \ “FK_dbo.Offices_dbo.Companies_CompanyId \”。冲突发生在 database \“PolicyManager \”,table \“dbo.Companies \”,列 'Id'。\ r \ n声明已经终止。“
当l hover model.Name我返回一个值但是其余的返回一个空值,我怀疑这是上述错误的原因。
可能会出现什么问题,因为我之前使用过相似的代码并且有效。愿任何人帮忙。提前谢谢
答案 0 :(得分:4)
您正在添加新办公室。
错误表明存在参照完整性问题使用Company表的外键约束。
创建订单时,您需要添加以下公司密钥:
CompanyId = user.CompanyId
因此,似乎user.CompanyId不是针对现有公司注册的ID。