在EF中创建对象,在DB中的saveChanges之后为null

时间:2016-06-20 08:03:50

标签: c# entity-framework

在我的审计上设置AuditReport并保存后,(在调试器中它填充了一个代理),数据库中仍然没有条目,我不明白为什么。以下是相关课程:

public class AuditReport
{
    [Key]
    [ForeignKey("Audit")]
    [Column("AuditReport_ID")]
    public int ID { get; set; }

    [Required]
    public virtual Audit Audit { get; set; }
}

public class Audit
{
    [Key]
    public int GeneratedID { get; set; }

    [Index("Audit_ID", IsUnique = true)]
    public int Audit_ID { get; set; }
    public virtual AuditReport AuditReport { get; set; }
}

新的AuditReport已创建的方法

public async override Task SaveChangesAsync()
{
   using (var dbAccess = new DatabaseAccess())
   {
        var foundAudit = dbAccess.Audits.Include("AuditReport").Include("AuditReport.Stellungnahmen").SingleOrDefault(_ => _.Audit_ID == Audit.Audit_ID);
        if (foundAudit != null)
        {
            if (foundAudit.AuditReport == null)
            {
                foundAudit.AuditReport = dbAccess.AuditReports.Create();
                foundAudit.AuditReport.Audit = foundAudit;
            }                      
            else
            foundAudit.AuditReport.Stellungnahmen.ToList().ForEach(_ => dbAccess.Entry(_).State = EntityState.Deleted);

            foreach (var item in Stellungnahmen.Where(_ => _.IsChecked == true))
                    foundAudit.AuditReport.Stellungnahmen.Add(dbAccess.Stellungnahmen.SingleOrDefault(_ => _.KeyWord == item.KeyWord));
            }
        await dbAccess.SaveChangesAsync();
    }
}

正如我已经说过的,我已经调试了它,一切看起来都很好。

1 个答案:

答案 0 :(得分:0)

尝试删除ID上的[Key],因为您已经[ForeignKey] atrribute。