c# - 将唯一值从 EF 插入数据库
问题描述
我正在使用 Razor 页面创建一个 CRUD 应用程序。我正在使用基于 SQL 的数据库。我不想让工具具有相同的工具编号。如果可能,异常处理将是理想的。获取一条消息,其中显示“工具编号已存在”等。
IDENTITY(1,1)
在编辑工具时,我收到此错误消息:
SqlException:无法更新标识列“ToolNumber”。
UNIQUE 当我为两个工具设置相同的工具编号时,我收到以下错误消息:
SqlException:违反 UNIQUE KEY 约束“UQ__TOOL__F63D0498394D4BBD”。无法在对象“dbo.TOOL”中插入重复键。重复键值为 (1)。
这是我的Tool
实体:
public class Tool
{
[Required(ErrorMessage = "RFID Kode kreves")]
public long ToolId { get; set; }
[Required(ErrorMessage = "Verktøynummer kreves")]
public int ToolNumber { get; set; }
[Required(ErrorMessage = "Model navn kreves")]
[StringLength(20, MinimumLength = 3, ErrorMessage = "Maksimal lengde 20 bokstaver")]
public string? Model { get; set; }
public bool Borrowed { get; set; }
[StringLength(20, MinimumLength = 3, ErrorMessage = "Maksimal lengde 20 bokstaver")]
public string? Manufacturer { get; set; }
[Required(ErrorMessage = "Verktøy kategori kreves")]
[StringLength(20, MinimumLength = 3, ErrorMessage = "Maksimal lengde 20 bokstaver")]
public string Category { get; set; }
public long EmployeeId { get; set; }
[StringLength(30, MinimumLength = 3, ErrorMessage = "Maksimal lengde 30 bokstaver")]
public string? EmployeeName { get; set; }
public string? Description { get; set; }
[StringLength(20, MinimumLength = 3, ErrorMessage = "Maksimal lengde 20 bokstaver")]
public string? SerialNumber { get; set; }
public DateTime? DateOfPurchase { get; set; }
public int? Reminder { get; set; }
public string? Price { get; set; }
[StringLength(10, MinimumLength = 0, ErrorMessage = "Maksimal lengde 10 bokstaver")]
public string? Condition { get; set; }
public DateTime? DateOfCalibration { get; set; }
public string? CalibrationPlace { get; set; }
public string? PhotoPath { get; set; }
}
这是我的添加方法:
public Tool Add(Tool newTool)
{
context.TOOL.Add(newTool);
context.SaveChanges();
return newTool;
}
这是我的更新方法:
public Tool Update(Tool updatedTool)
{
var tool = context.TOOL.Attach(updatedTool);
tool.State = Microsoft.EntityFrameworkCore.EntityState.Modified;
context.SaveChanges();
return updatedTool;
}
解决方案
您可以在使用相同的 ToolNumber 添加/更新之前验证数据库中是否有任何工具并引发自定义异常。
public class DuplicatedException : Exception
{
public DuplicatedException()
{
}
public DuplicatedException(string message)
: base(message)
{
}
public DuplicatedException(string message, Exception inner)
: base(message, inner)
{
}
}
方法:
public Tool Add(Tool newTool)
{
if (context.TOOL.FirstOrDefault(t => t.ToolNumber == newTool.ToolNumber))
throw new DuplicatedException("Toolnumber already exists");
context.TOOL.Add(newTool);
context.SaveChanges();
return newTool;
}
public Tool Update(Tool updatedTool)
{
if (context.TOOL.FirstOrDefault(t => t.ToolNumber == updatedTool.ToolNumber && t.ToolId != updatedTool.ToolId))
throw new DuplicatedException("Toolnumber already exists");
var tool = context.TOOL.Attach(updatedTool);
tool.State = Microsoft.EntityFrameworkCore.EntityState.Modified;
context.SaveChanges();
return updatedTool;
}
推荐阅读
- xml - 使用 XSLT 将 XML 转换为 CSV
- c++ - C++ RVO 是否适用于 auto[x,y] = my_func()?
- python - 以秒 (?) 为单位的 datetime 列转换为 pandas 日期时间
- python - 使用边缘检测创建一个 numpy 掩码
- symfony - 子文件夹中的刺激控制器在 Symfony 中不起作用
- firebase - FirebaseError:权限缺失或不足。只读
- android - 无法在 Android 设备或模拟器上启动 React Native App。错误:spawnSync adb ENOENT
- asp.net - InvalidOperationException:无法解析类型“Microsoft.AspNetCore.Identity.UserManager`1[AspNetCoreTodo.Models.ApplicationUser]”的服务
- nlp - 在特定领域继续训练预训练的 BERT 模型的最简单方法是什么?
- r - "as.data.frame.default(x[[i]], optional = TRUE) 中的错误:使用 gamlss 函数(或 lme())时无法将类“函数”强制转换为 data.frame”