简体   繁体   English

实体框架核心:当IDENTITY_INSERT设置为OFF时,无法为表'Relation'中的Identity列插入显式值

[英]Entity framework core: Cannot insert explicit value for identity column in table 'Relation' when IDENTITY_INSERT is set to OFF

I'm bulding an application and when I want to insert a form into my form table I get the following error: 我正在建立一个应用程序,当我想将表单插入到表单表中时,出现以下错误:

Cannot insert explicit value for identity column in table 'Relation' when IDENTITY_INSERT is set to OFF. 当IDENTITY_INSERT设置为OFF时,无法为表'Relation'中的Identity列插入显式值。

These are my models: 这些是我的模型:

Form model: 表格模型:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [ForeignKey("FormType")]
    public int? TypeId { get; set; }
    public virtual FormType Type { get; set; }

    [ForeignKey("FormStatusType")]
    public int? StatusTypeId { get; set; }
    public virtual FormStatusType StatusTknype { get; set; }

    [ForeignKey("Relation")]
    public int? SupplierId { get; set; }
    public virtual Relation Supplier { get; set; }

    [ForeignKey("Relation")]
    public int? CustomerId { get; set; }
    public virtual Relation Customer { get; set; }

    public String SupplierReference { get; set; }
    public Guid ApiId { get; set; }
    public DateTime DueDate { get; set; }
    public FormFile FormFiles { get; set; }
    public String FormName { get; set; }
    public DateTime UploadDate { get; set; }

Relation model: 关系模型:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [ForeignKey("FormType")]
    public int? TypeId { get; set; }
    public virtual FormType Type { get; set; }

    [ForeignKey("FormStatusType")]
    public int? StatusTypeId { get; set; }
    public virtual FormStatusType StatusTknype { get; set; }

    [ForeignKey("Relation")]
    public int? SupplierId { get; set; }
    public virtual Relation Supplier { get; set; }

    [ForeignKey("Relation")]
    public int? CustomerId { get; set; }
    public virtual Relation Customer { get; set; }

    public String SupplierReference { get; set; }
    public Guid ApiId { get; set; }
    public DateTime DueDate { get; set; }
    public FormFile FormFiles { get; set; }
    public String FormName { get; set; }
    public DateTime UploadDate { get; set; }

My context looks like this: 我的上下文如下所示:

public class DataContext: DbContext
{
    public DataContext(DbContextOptions<DataContext> options): base(options)
    {

    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
        optionsBuilder.UseSqlServer();
    }

    public DbSet<Relation> Relation { get; set; }
    public DbSet<Setting> Settings { get; set; }
    public DbSet<Notification> Notification { get; set; }
    public DbSet<FormStatusType> FormStatusType { get; set; }
    public DbSet<File> File { get; set; }
    public DbSet<FormFile> FormFile { get; set; }
    public DbSet<FormType> FormType { get; set; }
    public DbSet<Form> Form { get; set; }
    public DbSet<User> User { get; set; }
    public DbSet<RelationUser> RelationUser { get; set; }
    public DbSet<SupplierCustomer> SupplierCustomer { get; set; }

}

The method I use to add a form looks like this: 我用来添加表单的方法如下所示:

 public async Task<Form> AddForm(Form form, int currentUserId)
    {
        try
        {
            if (form != null)
            {
                //huidige gebruiker als supplier aanduiden
                Relation r = await GetCurrentUser(currentUserId);
                form.Supplier = r;
                form.SupplierId = r.Id;

                //form aan de db toevoegen
                _datacontext.Form.Add(form);
                _datacontext.SaveChanges();

                return form;
            }
            else
            {
                return null;
            }
        }
        catch (Exception e)
        {
            LogError(e);
            return null;
        }
    }

The get current user method 获取当前用户方法

 private async Task<Relation> GetCurrentUser(int currentUserId)
    {
        var relation = from r in _datacontext.RelationUser
                       where r.UserId == currentUserId
                       select r.Relation;
        return await relation.FirstOrDefaultAsync();
    }

This is where I call the AddForm method: 这是我调用AddForm方法的地方:

 [HttpPost]
    [Route("addform")]
    [Authorize]
    // api/form/addform
    public async Task<IActionResult> AddForm([FromBody] Form form)
    {
        if (ModelState.IsValid)
        {
            Form f = await _formRepository.AddForm(form, GetUserIdFromToken());

            if(f != null)
            {
                QueueObject qo = new QueueObject()
                {
                    ActionTypeId = 1,
                    FormId = f.Id
                };
                await new QueueHandler().SendMessageToQueue(qo);
            }

            return Ok(f);
        }
        else
        {
            return NotFound("model is niet geldig");
        }
    }

I already searched but found nothing that solved the problem 我已经搜索过,但没有找到解决问题的方法

You have multiple errors on your model. 您的模型有多个错误。 The ForeignKey attribute must point to properties in the class, not to the type of the dependent entity: ForeignKey属性必须指向类中的属性,而不是依赖实体的类型:

//FORM MODEL
[ForeignKey("Type")]
public int? TypeId { get; set; }
public virtual FormType Type { get; set; }

[ForeignKey("StatusTknype")]
public int? StatusTypeId { get; set; }
public virtual FormStatusType StatusTknype { get; set; }

[ForeignKey("Supplier")]
public int? SupplierId { get; set; }
public virtual Relation Supplier { get; set; }

[ForeignKey("Customer")]
public int? CustomerId { get; set; }
public virtual Relation Customer { get; set; }

//RELATION MODEL
[ForeignKey("Type")]
public int? TypeId { get; set; }
public virtual FormType Type { get; set; }

[ForeignKey("StatusTknype")]
public int? StatusTypeId { get; set; }
public virtual FormStatusType StatusTknype { get; set; }

[ForeignKey("Relation")]
public int? SupplierId { get; set; }
public virtual Relation Supplier { get; set; }

[ForeignKey("Customer")]
public int? CustomerId { get; set; }
public virtual Relation Customer { get; set; }

Also, if you followed Convention Over Configuration , you could drop the ForeignKeyAttribute completely by just naming the properties conventionally: 另外,如果遵循Convention over Configuration ,则可以仅按常规方式命名属性来完全删除ForeignKeyAttribute:

public int? StatusTypeId { get; set; }
public virtual FormStatusType StatusType { get; set; }

Another possible reason this may happen, is if you have a timeout in some call to SaveChanges when trying to insert new entities to your database, then try calling SaveChanges again, using the same DbContext instance. 发生这种情况的另一个可能原因是,如果您在尝试向数据库中插入新实体时对SaveChanges某些调用超时,然后尝试使用相同的DbContext实例再次调用SaveChanges

This is reproducible: 这是可重现的:

using(var context = new MyDbContext())
{
    context.People.Add(new Person("John"));
    try
    {
        // using SSMS, manually start a transaction in your db to force a timeout
        context.SaveChanges();
    }
    catch(Exception)
    {
        // catch the time out exception
    }
    // stop the transaction in SSMS
    context.People.Add(new Person("Mike"));
    context.SaveChanges(); // this would cause the exception
}

This last SaveChanges would cause Cannot insert explicit value for identity column in table 'People' when IDENTITY_INSERT is set to OFF . 当IDENTITY_INSERT设置为OFF时,最后一次SaveChanges将导致无法在表'People'中为标识列插入显式值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当 IDENTITY_INSERT 设置为 OFF 时,无法为标识列插入显式值。 (实体框架核心) - Cannot insert explicit value for identity column when IDENTITY_INSERT is set to OFF. (Entity Framework Core) 实体框架:当IDENTITY_INSERT设置为OFF时,无法为表&#39;[table]&#39;中的标识列插入显式值 - Entity Framework: Cannot insert explicit value for identity column in table '[table]' when IDENTITY_INSERT is set to OFF Entity Framework Core 6 - 当 IDENTITY_INSERT 设置为 OFF 时,无法在表“角色”中插入标识列的显式值 - Entity Framework Core 6 - Cannot insert explicit value for identity column in table 'Roles' when IDENTITY_INSERT is set to OFF 当IDENTITY_INSERT设置为OFF时,无法在TABLE中为Identity列插入显式值; .NET Core 2.1 - Cannot insert explicit value for identity column in TABLE when IDENTITY_INSERT is set to OFF; .NET Core 2.1 使用现有数据库和实体框架的代码优先:当IDENTITY_INSERT设置为OFF时,无法为表中的标识列插入显式值 - Code First With Existing Database, Entity Framework: Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF 实体框架抛出无法为表中的“身份”列插入显式值…IDENTITY_INSERT设置为OFF时错误 - Entity Framework Throwing Cannot Insert Explicit Value for Identity Column In Table … When IDENTITY_INSERT is set to OFF Error SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法为表 [表名] 中的标识列插入显式值 - SqlException: Cannot insert explicit value for identity column in table [Table name] when IDENTITY_INSERT is set to OFF 出现错误:当IDENTITY_INSERT设置为OFF时,无法在表&#39;Table&#39;中为标识列插入显式值 - Getting Error: Cannot insert explicit value for identity column in table 'Table' when IDENTITY_INSERT is set to OFF 当IDENTITY_INSERT设置为OFF时,无法为表&#39;ActivityInstances中的标识列插入显式值 - Cannot insert explicit value for identity column in table 'ActivityInstances' when IDENTITY_INSERT is set to OFF SqlException:当IDENTITY_INSERT设置为OFF时,无法为表&#39;Recipe&#39;中的Identity列插入显式值 - SqlException: Cannot insert explicit value for identity column in table 'Recipe' when IDENTITY_INSERT is set to OFF
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM