c# - 使用实体框架更新一条记录
问题描述
我想使用实体框架将一条记录更新到数据库。当更新此员工的所有日期时,仅设置 Null 员工代码和 IsActive .. 如何仅更新 isAcive
这是我的代码
private void btn_Save_Resignation_Click(object sender, EventArgs e)
{
try
{
var IsActive = new database.tblEmployeeData
{
EmployeeCode = Convert.ToInt32(txtEmpCode.Text),
IsActive = cbxResignationEmp.Checked = true,
};
db.tblEmployeeDatas.AddOrUpdate(IsActive);
db.SaveChanges();
MessageBox.Show("تم إقالة الموظف بنجاح", "Sigma Software", MessageBoxButtons.OK, MessageBoxIcon.Information);
ClearResignation();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Sigma Software", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
..................这是我的模型课
public partial class tblEmployeeData
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public tblEmployeeData()
{
this.tblBlackListForEmps = new HashSet<tblBlackListForEmp>();
this.tblContractForEmploees = new HashSet<tblContractForEmploee>();
this.tblCustodyForEmps = new HashSet<tblCustodyForEmp>();
this.tblDocumentEmployeeWithStates = new HashSet<tblDocumentEmployeeWithState>();
this.tblOtherDataForEmps = new HashSet<tblOtherDataForEmp>();
this.tblPenaltyForEmployees = new HashSet<tblPenaltyForEmployee>();
}
public int EmployeeCode { get; set; }
public string EmployeeName { get; set; }
public Nullable<byte> GenderCode { get; set; }
public Nullable<byte> PranchCode { get; set; }
public Nullable<byte> RelationShipCode { get; set; }
public Nullable<byte> AdministrationCode { get; set; }
public Nullable<byte> DepartmentCode { get; set; }
public Nullable<short> JopCode { get; set; }
public Nullable<byte> JopLevelCode { get; set; }
public Nullable<byte> ConCustmerCode { get; set; }
public Nullable<byte> NationalityCode { get; set; }
public Nullable<byte> TypeOfWorkersCode { get; set; }
public Nullable<bool> IsActive { get; set; }
解决方案
如此处所述:
Entity Framework 不会神奇地找出哪些属性已更改与哪些属性未更改,它获取实体,如果存在,则将实体输入到当前填充的数据库中。如果实体不存在,则将其插入数据库。
因此,我建议您通过以下方式更改代码:
var empCode = Convert.ToInt32(txtEmpCode.Text);
var IsActive = db.tblEmployeeDatas.FirstOrDefault(e => e.EmployeeCode == empCode);
if (IsActive == null)
{
IsActive = new database.tblEmployeeData
{
EmployeeCode = empCode,
};
}
IsActive.IsActive = cbxResignationEmp.Checked = true, // BTW should it be assigning or condition?
db.tblEmployeeDatas.AddOrUpdate(IsActive);
db.SaveChanges();
...
推荐阅读
- r - 用 ggplot 和 2 个过滤器叠加 2 个条形图
- c# - 如何为外出请求 ASP.net c# 添加动态标头?
- laravel - 使用 \Mail::send 不能设置标题
- android - 如何通过单击按钮重试方法?
- yarnpkg - yarnpkg 是 node.js 包管理器 yarn 的别名吗?
- python - Lifetimes 包给出不一致的结果
- ios - 如何检查当前 viewController 或根 viewController?
- objective-c - Tableviewcell如何为项目组提供备用单元格颜色
- google-sheets - Google 表格中财务数据的自定义聚合
- postman - 是否可以在本地使用预请求创建邮递员环境范围?