49

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.

janhartmann
  • 14,713
  • 15
  • 82
  • 138

5 Answers5

55

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.

Mike Circuitry
  • 840
  • 8
  • 9
  • 2
    In my case, I was setting a field to a string longer than the limit specified in my context configuration. – redcurry Nov 09 '15 at 20:32
  • Similar in my case, I have a field with a default value in my database, however, I still receive this exception if I leave the corresponding property of the model null. It doesn't make sense to me, I expected EF to be smart enough to figure it out. – VincentZHANG Sep 24 '16 at 03:43
  • This error does almost always result from a bad value being provided. You will find the error in the exception. Do a quick watch and dig through its properties. I wish I could remember exactly where it was, but I promise the specific field is in the exception. – Jeremy Ray Brown Oct 24 '16 at 15:46
  • @VincentZHANG I can help you there. EF doesn't figure it out, but if you go into the edmx model browser you can set the default value to the same as the database, it'll then work. – Justin Doyle Oct 18 '17 at 00:06
  • Or you can just check the datatype in the database.... (assuming you have access to it and SQL Server Management Studio to connect to it) – vapcguy Sep 18 '18 at 17:23
  • Note to self: in other words check to make sure that if the table mapped to the entity has a column in the database which is not null and you aren't supplying a value when creating the entity. – robbpriestley Oct 12 '18 at 20:38
53

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

dan-iel
  • 801
  • 8
  • 4
6

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.

Chad
  • 1,512
  • 1
  • 16
  • 40
1

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.

Joma
  • 3,520
  • 1
  • 29
  • 32
1

whene exception occured, in visual studio, press shift+F9 and look for:

$exception.EntityValidationErrors.First().ValidationErrors.First().ErrorMessage
$exception.EntityValidationErrors.First().ValidationErrors.First().PropertyName

or in your code

try
{
    //Your code
}
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
    var errorMessage = ex.EntityValidationErrors.First().ValidationErrors.First().ErrorMessage;
    var propertyName = ex.EntityValidationErrors.First().ValidationErrors.First().PropertyName;
}
catch (Exception ex)
{
    //other error
    throw ex;
}

it is only extend of dan-iel response

Morteza
  • 2,378
  • 5
  • 26
  • 37