0

当我尝试在我的一个关系表中插入新行时出现以下错误。我有以下两个模型:

public class CompanyCredit
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int creditId { get; set; }

    public int planCredit { get; set; }
    public DateTime? PlanCreditExpirationDate { get; set; }

}

public class CompanyInformation
{

    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int id { get; set; }

    [Required]
    [DisplayName("Company Name:")]
    public string companyName { get; set; }

    public string timeZone { get; set; }

    //navigation Properties       
    public virtual CompanyCredit Credits { get; set; }
}

而 dbContext 中的这个关系

modelBuilder.Entity<CompanyInformation>().HasOptional(e => e.Credits);

我正在尝试在 CompanyCredit 表中添加一条记录,如下所示:

if (_company.Credits == null)
{
   var _credits = new CompanyCredit();
   _credits.planCredit = 200;
   _credits.PlanCreditExpirationDate = System.DateTime.UtcNow.AddMonths(1);

   _company.Credits = _credits;
   repo.InsertOrUpdate(_company, User.Identity.Name);
 }

最后插入或更新只是将公司标记为已更改,并将 _credit 标记为添加,如下所示:

 _db.Entry(_credits).State = System.Data.EntityState.Added;
 _db.Entry(Company).State = System.Data.EntityState.Modified;
 _db.SaveChanges();

当它运行时,我得到以下错误,我似乎找不到原因。

 Cannot insert the value NULL into column 'creditId', table 'Project.dbo.CompanyCredits'; column does not allow nulls. INSERT fails.

该语句已终止。

提前感谢您的帮助。

4

2 回答 2

2

我发现问题出在属性中,[DatabaseGenerated(DatabaseGeneratedOption.Identity)]这应该是[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 我想我会发布这个,这样其他人可能会从中受益。

于 2013-06-13T07:42:35.603 回答
0

Could you please try reversing the order of entity state modification, just before the saveChanges call

 _db.Entry(Company).State = System.Data.EntityState.Modified;
 _db.Entry(_credits).State = System.Data.EntityState.Added;
 _db.SaveChanges();
于 2013-05-07T00:45:30.433 回答