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:
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With