我有一个像这样定义的 EntityFrameworkCore.Triggered 触发器,如果 (firstName.Length > 1 && lastName.Length > 1) 不真实,我想取消插入/更新
namespace MMSP_Providers.Data.Triggers
{
public class EnsureInterlocutorNameUniformity : IBeforeSaveTrigger<Interlocutor>
{
public Task BeforeSave(ITriggerContext<Interlocutor> context, CancellationToken cancellationToken)
{
if (context.ChangeType == ChangeType.Added || context.ChangeType == ChangeType.Modified)
{
string firstName = context.Entity.FirstName, lastName = context.Entity.LastName;
if (firstName.Length > 1 && lastName.Length > 1)
{
context.Entity.FirstName = char.ToUpper(firstName[0]) + firstName[1..];
context.Entity.LastName = lastName.ToUpper();
}
else
{
// Cancel
}
}
return Task.CompletedTask;
}
}
}
我尝试如下:
public class StudentSignupTrigger : IBeforeSaveTrigger<Student>
{
private readonly EFTriggerContext _applicationDbContext;
public StudentSignupTrigger(EFTriggerContext applicationDbContext)
{
_applicationDbContext = applicationDbContext;
}
public Task BeforeSave(ITriggerContext<Student> context, CancellationToken cancellationToken)
{
if (context.ChangeType == ChangeType.Added || context.ChangeType == ChangeType.Modified)
{
string firstName = context.Entity.FirstName, lastName = context.Entity.LastName;
if (firstName.Length > 1 && lastName.Length > 1)
{
context.Entity.FirstName = char.ToUpper(firstName[0]) + firstName[1..];
context.Entity.LastName = lastName.ToUpper();
}
else
{
if(context.ChangeType == ChangeType.Added)
{
_applicationDbContext.Student.Remove(context.Entity);
}
if (context.ChangeType == ChangeType.Modified)
{
_applicationDbContext.Entry(context.Entity).Property(x => x.FirstName).IsModified = false;
_applicationDbContext.Entry(context.Entity).Property(x => x.LastName).IsModified = false;
}
}
}
return Task.CompletedTask;
}
}
结果1: