gpt4 book ai didi

c# - Entity Framework 核心 : Cannot insert explicit value for identity column in table 'Relation' when IDENTITY_INSERT is set to OFF

转载 作者:行者123 更新时间:2023-11-30 20:30:54 25 4
gpt4 key购买 nike

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

Cannot insert explicit value for identity column in table 'Relation' when IDENTITY_INSERT is set to 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");
}
}

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

最佳答案

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

这是可重现的:

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
}

最后一个 SaveChanges 会导致当 IDENTITY_INSERT 设置为 OFF 时无法为表“People”中的标识列插入显式值

关于c# - Entity Framework 核心 : Cannot insert explicit value for identity column in table 'Relation' when IDENTITY_INSERT is set to OFF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44051764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com