【发布时间】:2020-08-12 14:20:35
【问题描述】:
我将 Mircosoft SSMS 用于我的 sql 服务器,将 ASP.NET CORE 用于我的网站。
下面的查询是我的删除触发器。但是,每当我尝试删除网站中的某些内容时,就会弹出此错误:“InvalidCastException:无法将 'System.Guid' 类型的对象转换为 'System.Int32' 类型。”
删除触发器:
create trigger Branch_Delete
on Branch
after delete
as
begin
set nocount on;
declare @BranchID uniqueidentifier
select @BranchID = deleted.BranchID
from deleted
insert into AuditLog(TableName, ModifiedBy, AuditDateTime , ID ,AuditAction)
Values
('Branch', SUSER_SNAME(), GETDATE(), @BranchID ,'Delete')
select BranchID from Deleted
end
型号:
namespace Test.Models
{
public class BranchModel
{
[Key]
[Display(Name = "Branch ID")]
public Guid BranchID { get; set; }
[Required(ErrorMessage = "Please Enter The Branch Name ..")]
[Display(Name = "Branch Name")]
public string BranchName { get; set; }
[Required(ErrorMessage = "Please Enter The Branch Address ..")]
[Display(Name = "Branch Address")]
public string BranchAddress { get; set; }
}
}
控制器(用于删除功能):
public async Task<IActionResult> DeleteBranch(Guid? id)
{
if (id == null)
{
return NotFound();
}
var branchModel = await _context.Branch
.FirstOrDefaultAsync(m => m.BranchID == id);
if (branchModel == null)
{
return NotFound();
}
return View(branchModel);
}
// POST: BranchModels/Delete/5
[HttpPost, ActionName("DeleteBranch")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmedBranch(Guid id)
{
var branchModel = await _context.Branch.FindAsync(id);
_context.Branch.Remove(branchModel);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Branch));
}
【问题讨论】:
-
您能否确认“var branchModel = await _context.Branch .FirstOrDefaultAsync(m => m.BranchID == id);”正在返回一个 BranchModel 类型?
-
不确定您的 Branch 对象/表是如何定义的,但我猜它被定义为一个 int。由于 GUID 是一个 16 字节的数值,而 int 只有 4,这些不兼容(自动)转换。
标签: c# sql-server asp.net-core triggers ssms