【问题标题】:Update Row - check if it Exists Else Insert Logic with Entity Framework更新行 - 检查它是否存在 否则使用实体框架插入逻辑
【发布时间】:2023-01-25 00:48:30
【问题描述】:

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

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

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

}

【问题讨论】:

  • “什么是最好的实施方式”这将使您的问题立即因“自以为是”而被关闭。您可以选择说“如何……”或“我该如何……”。
  • 英孚还是英孚核心? - 可能存在差异。

标签: c# sql entity-framework entity-framework-core


【解决方案1】:

将 DbContext 类注入控制器并在控制器方法中处理逻辑

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

【讨论】:

  • 不要忘记在交易中这样做。它不是原子的。
  • 已添加交易代码
猜你喜欢
  • 2011-07-30
  • 1970-01-01
  • 2010-10-12
  • 2016-02-29
  • 1970-01-01
  • 1970-01-01
  • 2012-11-12
  • 2011-08-31
  • 1970-01-01
相关资源
最近更新 更多