首页 > 解决方案 > 自动插入记录到另一个表

问题描述

我有名为 AdditionalInsuranceLog、AdditionInsurance 和 Patient 的表

附加保险日志.cs

public partial class additionalInsuranceLog 
    {
        public long PatientId { get; set; }
        public byte AdditionInsuranceId { get; set; }
        public DateTime ChangeDate { get; set; }

        public virtual AdditionInsurance AdditionInsurance { get; set; }
        public virtual Patient Patient { get; set; }
    }

加法保险.cs

public partial class AdditionInsurance
    {
        public AdditionInsurance()
        {
            Patient = new HashSet<Patient>();
        }

        public byte Id { get; set; }
        public string Name { get; set; }

        public virtual ICollection<Patient> Patient { get; set; }
    }

病人.cs

public partial class Patient
    {
        public Patient()
        {
        }
        public long Id { get; set; }
        public string NationalCode { get; set; }
        public string FName { get; set; }
        public string LName { get; set; }        
        public string Education { get; set; } 
        public string CellPhone { get; set; }
        public byte? AdditionInsurance { get; set; }        
        public DateTime EditDate { get; set; }

        public AdditionInsurance AdditionInsuranceNavigation { get; set; }
    }

AdditionInsurance 填写在 sql 中,我希望每次在 db 中插入或更新患者记录,如果 AdditionInsurance 字段发生更改,则会在附加保险日志表中插入一条新记录,日期为今天,我在我的多个地方插入或更新患者表web 应用程序,我想要一个最佳解决方案,而不是在我更新或插入患者记录的任何地方进行编码以在 additionalInsuranceLog 中插入记录我希望它始终完成,是否有最佳解决方案?

我正在使用 asp.net core 3 和 entityframework core

更新 我对触发器一无所知,我应该或可以将触发器用于我的目的吗?请告诉我有关如何做的详细信息?

标签: sql-serverentity-framework-coreasp.net-core-mvc

解决方案


是的,您可以使用触发器。

像这样的东西。

CREATE TRIGGER AdditionInsurance_trg
ON AdditionInsurance 
AFTER UPDATE,INSERT
AS 
BEGIN
    INSERT INTO AdditionalInsuranceLog(
        PatientID,
        Field1New,
        Field1old)
    SELECT 
        i.PatientID,
        i.Field1New,
        d.Field1Old        
    FROM inserted i
    LEFT JOIN deleted d
        ON i.item_id = d.item_id
   END;

推荐阅读