Home > OS >  How to cancel insertion/update in an EntityFrameworkCore.Triggered before save trigger
How to cancel insertion/update in an EntityFrameworkCore.Triggered before save trigger

Time:08-19

I have an EntityFrameworkCore.Triggered trigger defined like this, I want to cancel the insertion/update if (firstName.Length > 1 && lastName.Length > 1) is not truthy

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;
        }
    }
}

CodePudding user response:

I tried as below:

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;
    }
}

Result1:

enter image description here Result2: enter image description here

  • Related