【发布时间】:2020-11-28 10:35:28
【问题描述】:
我正在创建这个 TaskManager 应用,并且我已经设置了模型类、dbcontext 和表单。
当我在页面本身上按提交按钮 2 次时,我收到以下错误:
Microsoft.EntityFrameworkCore.DbUpdateException: '更新条目时出错。有关详细信息,请参阅内部异常。'
内部异常:
SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法在表“Tasks”中插入标识列的显式值。
@page "/task/createtask"
@inject AppDbContext _context;
<h3>Create a Task</h3>
<EditForm Model="@taskModel" OnValidSubmit="@HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<div class="form-group">
<label for="TitleTb">Enter the title:</label>
<InputText id="TitleTb" class="form-control" @bind-Value="taskModel.Title"></InputText>
<label for="DescTb">Enter the description:</label>
<InputText id="DescTb" class="form-control" @bind-Value="taskModel.Description"></InputText>
<label for="SelectTb"> <span class="text-warning">optional</span> Enter the priority level:</label>
<InputSelect id="SelectTb" class="form-control" @bind-Value="taskModel.ImportanceType">
<option value="">Select priority...</option>
<option value="1" class="text-danger">Very important</option>
<option value="2" class="text-warning">Can wait</option>
<option value="3" class="text-primary">Not that important</option>
</InputSelect>
<br/>
<button type="submit" class="btn btn-primary">Submit!</button>
</div>
</EditForm>
@code {
private TaskModel taskModel = new TaskModel();
private void HandleValidSubmit()
{
taskModel.IsCompleted = false;
taskModel.DateCreated = DateTime.Today;
_context.Tasks.Add(taskModel);
_context.SaveChanges();
}
}
模型和上下文:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace TaskManagerApp.Models
{
public class TaskModel
{
[Key]
[Required]
public int Id { get; set; }
[Required]
[MaxLength(20)]
[MinLength(3)]
public string Title { get; set; }
[MaxLength(150)]
[MinLength(5)]
public string Description { get; set; }
public DateTime DateCreated { get; set; }
[Required]
public bool IsCompleted { get; set; }
public string ImportanceType { get; set; }
}
}
数据库上下文:
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TaskManagerApp.Models;
namespace TaskManagerApp.Data
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<TaskModel> Tasks { get; set; }
}
}
我还使用了 2 个 dbcontext,一个来自 Microsoft 身份验证系统身份,另一个来自我创建的名为 AppDbContext。
有什么办法可以解决吗?如果是,我将非常感谢您的帮助!
谢谢!
【问题讨论】:
-
那么你说只按一次按钮就有效吗?
-
不,它只是没有保存到数据库中。它已经解决了。谢谢你的回答!
-
嗨,Isaac,您能否记录下这个问题的未来查看者的解决方案。
标签: c# entity-framework-core blazor blazor-server-side