如何在 EntityFrameworkCore 中取消插入/更新。在保存触发器之前触发

问题描述 投票:0回答:1

我有一个像这样定义的 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;
        }
    }
}
c# asp.net-core entity-framework-core triggers entity-framework-core.triggered
1个回答
0
投票

我尝试如下:

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:

enter image description here 结果2: enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.