实体框架核心:无法在表格中插入标识列的显式值'关系'当IDENTITY_INSERT设置为OFF时

时间:2017-05-18 15:19:02

标签: c# .net entity-framework-core

我正在构建一个应用程序,当我想在表格表中插入表单时,我收到以下错误:

  

无法在表格中插入标识列的显式值'关系'   当IDENTITY_INSERT设置为OFF时。

这些是我的模特:

表单模型:

[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; }

关系模型:

[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; }

我的上下文如下:

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; }

}

我用来添加表单的方法如下所示:

 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;
        }
    }

获取当前用户方法

 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();
    }

这是我调用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");
        }
    }

我已经搜索过,但没有找到解决问题的方法

2 个答案:

答案 0 :(得分:2)

您的模型有多处错误。 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; }

此外,如果您按照约定优于配置,您可以通过按常规命名属性来完全删除ForeignKeyAttribute:

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

答案 1 :(得分:1)

发生这种情况的另一个可能原因是,如果您在尝试向数据库中插入新实体时对SaveChanges的某些调用超时,然后尝试使用相同的{{ 1}}实例。

这是可重复的:

SaveChanges

最后一个DbContext将导致当IDENTITY_INSERT设置为OFF时,无法为表“人物”中的身份列插入显式值