I wanna update one record to database using entity framework . when update this record all date for this employee set Null Only Employee Code And IsActive .. how update isAcive only
this is My Code
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);
}
}
................. This is my model class
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; }
As explained here:
Entity Framework does not magically figure out which properties have changed vs. which properties have not changed, it takes the entity, and if it exists, enters the entity into the database as it’s currently populated. If the entity does not exist, it inserts it into the database.
So I would recommend you to change your code in the next way:
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();
...