Home Ask Login Register

Developers Planet

Your answer is one click away!

Tom February 2016

Cannot insert explicit value for identity column in table 'ActivityInstances' when IDENTITY_INSERT is set to OFF

I am trying to insert a new ActivityInstance, I am not setting the ID, but entity framework is attempting to insert an ID anyway.

The model creation and save command:

        var ai = new ActivityInstance
            ActivityId = 1,
            LocationId = 1,
            BeginDate = DateTime.Now,
            ExpirationDate = DateTime.Now

The Model

public class ActivityInstance : IBusinessObject, IEntity
    public int Id { get; set; }
    public int LocationId { get; set; }
    public string TargetId { get; set; }
    public int ActivityId { get; set; }
    public DateTime? BeginDate { get; set; }
    public DateTime? ExpirationDate { get; set; }
    public Guid? DurableInstanceWorkflowId { get; set; }
    public int? TriggeredById { get; set; }
    public virtual Activity Activity { get; set; }
    public virtual Location Location { get; set; }
    public virtual MsdsDataValidation MsdsDataValidation { get; set; }
    public virtual ICollection<ResultsTransmittalQuestionAnswer> ActivityQuestionAnswers { get; set; }
    public virtual ICollection<ResultsTransmittalContact> ResultsTransmittalContacts { get; set; }
    public virtual Target Target { get; set; }
    public virtual CorrectiveActionPlan CorrectiveActionPlans { get; set; }
    public virtual FmVisit FmVisit { get; set; }
    public virtual AcknowledgeReport AcknowledgeReport { get; set; }
    public virtual SlCap SlCap { get; set; }
    public virtual FmVisitStudentRecordReview FmVisitStudentRecordReview { get; set; }
    public virtual ICollection<ActivityInstanceReminder> ActivityInstanceReminders { get; set; } 
   // public virtual InstancesTable Instances { get; set; }

The Mapping

    public ActivityInstanceMap()
        HasKey(x =        


bhmahler February 2016

Try adding the attributes to let it know that it is database generated

public int Id { get; set; }

Tom February 2016

Thanks to bhmahler's suggestion above I finally started looking into every relationship. One of the other programmers added the MsdsDataValidation and when they mapped the relationship they configured it backward. So in the MsdsDataValidationMap he had

            HasOptional(t => t.ActivityInstance)
            .WithRequired(t => t.MsdsDataValidation);

and should have had

            HasRequired(t => t.ActivityInstance)
            .WithOptional(t => t.MsdsDataValidation);

The back of his head will be smacked. Thanks for the help.

Post Status

Asked in February 2016
Viewed 2,513 times
Voted 10
Answered 2 times


Leave an answer

Quote of the day: live life