Home > Enterprise >  Foreign Key Constraint on database Save
Foreign Key Constraint on database Save

Time:09-17

I'm currently getting this error message:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_ViewDocumentAudit_UploadedDocuments". The conflict occurred in database "Butler", table "dbo.UploadedDocuments", column 'Id'. The statement has been terminated.

Here is my entity model - the UserId and DocumentId are both foreign keys:

public partial class ViewDocumentAudit
{
    public long Id { get; set; }
    public long UserId { get; set; }
    public int DocumentId { get; set; }
    public System.DateTime DateAccessed { get; set; }

    public virtual UploadedDocument UploadedDocument { get; set; }
    public virtual user user { get; set; }
}

Here is were I'm inserting a new record into the database:

public static void ViewDocumentAudit(long userId, int parsedDocumentId)
{
    using (Entities dbContext = new Entities())
    {
         ViewDocumentAudit auditObject = new ViewDocumentAudit();
         auditObject.UserId = userId;
         auditObject.DocumentId = parsedDocumentId;
         auditObject.DateAccessed = DateTime.Now;

         dbContext.ViewDocumentAudits.Add(auditObject);
         dbContext.SaveChanges();
     }
}

CodePudding user response:

"Presumably a document with the id parsedDocumentId doesn't exist in the UploadedDocuments table." – Llama

  • Related