OriginalValues不能用于对新增国家实体 [英] OriginalValues cannot be used for entities in the Added state

查看:433
本文介绍了OriginalValues不能用于对新增国家实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用实体框架来构建Web应用程序,在启动时创建了数据库和我的种子的方法增加了一些实体数据库中没有任何问题。该实体还检索工作没有任何问题。

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.

我的问题是,如果我试图从我的UI层创建一个实体,我遇到错误 OriginalValues不能用于对新增国家实体。该没有抛出异常的用户界面,但我发现,当我从问题挖周围

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.

我发生在我的:

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

    return entity;
}



截图:

Screenshot:

实体很小和映射:

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.

推荐答案

我遇到了这个问题一次,并通过检查,目前正在提交到数据库中的字段解决它。事实证明,我无意中试图插入一个空值成被设计为NOT NULL列。

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.

这篇关于OriginalValues不能用于对新增国家实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆