Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 835
janhartmann Avatar asked Mar 15 '14 09:03

janhartmann


2 Answers

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.

like image 82
Mike Circuitry Avatar answered Sep 21 '22 00:09

Mike Circuitry


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

like image 38
dan-iel Avatar answered Sep 20 '22 00:09

dan-iel