OriginalValues cannot be used for entities in the Added state [duplicate]

I am using Entity Framework to build an web application, the database is created on startup and my seed method adds some entities to the database without any problem. Also the retrieve of the entities is working without problems.

My problem is that if I try to create an entity from my UI layer, I come across the error OriginalValues cannot be used for entities in the Added state. The exception is not thrown to the UI, but I found it when I digged around from the problem.

I happens in my:

public virtual TEntity Add(TEntity entity)
{
    var entry = _context.Entry(entity);
    entry.State = EntityState.Added;
    _dbSet.Add(entity);

    return entity;
}

Screenshot:

enter image description here

The entity is very small and the mappings:

public abstract class EntityBase
{
    public int Id { get; set; }
}

public class AccessCode : EntityBase
{
    public string Code { get; set; }
    public int UsageCount { get; set; }
}

public class AccessCodeMapping : EntityTypeConfiguration<AccessCode>
{
    public AccessCodeMapping()
    {
        // Table
        ToTable("AccessCode");

        // Primary key
        HasKey(x => x.Id);

        // Properties
        Property(accesscode => accesscode.Code).IsRequired().HasMaxLength(256);
        Property(accesscode => accesscode.UsageCount).IsRequired();
    }
}

And this is how I create a test access code for demo purpose

var ac = new AccessCode {Code = "321", UsageCount = 0};
_accessCodeService.Create(ac);
_unitOfWork.Save();
return View("Login");

Can anyone figure out why this error is occurring? I'm lost. :-)

P.s Let me know if there is some pieces of code you wish to see.


I ran into this issue once, and resolved it by checking the fields that were being submitted to the database. It turns out that I inadvertently was attempting to insert a null value into a column that was designed as not null.


Under the exception, look for:

$exception.EntityValidationErrors[n].ValidationErrors[n].ErrorMessage
$exception.EntityValidationErrors[n].ValidationErrors[n].PropertyName

Where [n] is the array index (there may be more than one).

enter image description here


I ran into this issue and the reason was I was trying to fit a string of length 10 into a Varchar column that had been changed in the DB to 25 but was still in the Framework as 6. I removed the property and refreshed from the db and the problem went away.


Check if your model have outdated columns with not null constraint and which have null in the database, updating the model solve this issue.

Check if you are SubmitChanges() with a not null column when value is null.