简体   繁体   English

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

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

What is the best way to implement update row if it exists, else insert new row logic using Entity Framework?如果存在更新行,实现更新行的最佳方法是什么,否则使用实体框架插入新行逻辑?

Below is what I have done so far.以下是我到目前为止所做的。 I want to check, if any field in the existing employee database has changed then only update that record or if it is a new one add as a new row.我想检查,如果现有员工数据库中的任何字段已更改,则只更新该记录,或者如果它是新记录,则添加为新行。

Ex- Update the job title if it has changed, or add it as a new line if a new employee is added 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; }

}

Inject the DbContext class into your controller and handle your logic in a controller method将 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