繁体   English   中英

更新行 - 检查它是否存在 否则使用实体框架插入逻辑

[英]Update Row - check if it Exists Else Insert Logic with Entity Framework

如果存在更新行,实现更新行的最佳方法是什么,否则使用实体框架插入新行逻辑?

以下是我到目前为止所做的。 我想检查,如果现有员工数据库中的任何字段已更改,则只更新该记录,或者如果它是新记录,则添加为新行。

Ex- 如果职位名称发生变化则更新职位名称,如果添加了新员工则将其添加为新行

//DbContext

public class DataContext : DbContext
{
    public static string providerName = "System.Data.SqlClient";
    public DbSet<DisplayAPIDataEmployee>? Employee { get; set; }

    protected override void OnConfiguring(Microsoft.EntityFrameworkCore.DbContextOptionsBuilder optionBuilder)
    {
        optionBuilder.UseSqlServer("Server=;Initial Catalog = ;user id = ;password=");
    }

    protected override void OnModelCreating(Microsoft.EntityFrameworkCore.ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<DisplayAPIDataEmployee>().ToTable("Employee", e => e.IsTemporal());
    }
}
// Data model

[Table("Employee")]
public class DisplayAPIDataEmployee
{

    public DisplayAPIDataEmployee()
    {
        createdOn = DateTime.Now;
    }

    public DateTime ?createdOn { get; set; }
    public string ?displayName { get; set; }
    public string ?shortBirthDate { get; set; }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string employee_id { get; set; }

}

将 DbContext class 注入您的 controller 并在 controller 方法中处理您的逻辑

private readonly DataContext _context;

public Controller(DataContext _context) => this._context = _context;
...
// rest of your code
...
public void Test(string employee_id) {
    using DataContext dbContext = _context;
    using IDbContextTransaction transaction = dbContext.Database.BeginTransaction();

    try {
        DisplayAPIDataEmployee? employee = dbContext.Employee.FirstOrDefault(e => e.employee_id.Equals(employee_id));

        if (employee is null) {
            // add employee
            DisplayAPIDataEmployee add_employee = new(); //
            add_employee.employee_id = "";

            dbContext.Employee.AddRange(add_employee);
            dbContext.SaveChanges();
        }
        else {
            employee.employee_id = ""; // update employee property value

            dbContext.SaveChanges(); // entity 'employee' is tracked by EF Core and any saved changes to it is reflected to entity in Database.
        }

        transaction.Commit(); // commit all save changes if successful
    }
    catch (Exception ex)
    {
        transaction.Rollback(); // rollback in case of errors
        dbContext.ChangeTracker.Clear();

        // Log error
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM