Reputation: 50
Two tables are related as below. When I delete any user, only user will be deleted, and it's ok for me. When I delete any salary, all users related with this record will be deleted. I want to delete salary only.
class Employee
{
[Key]
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[Range(00000000000.00, 999999999999.00, ErrorMessage = "Amount must be between 00000000000.00 and 999999999999.00")]
public decimal Phone { get; set; }
public int SalaryId { get; set; }
public virtual Salary Salary { get; set; }
}
class Salary
{
[Key]
public int SalaryId { get; set; }
public string Name { get; set; }
[Range(0.01, 100000000.00, ErrorMessage = "Amount must be between 0.01 and 100000000.00")]
public decimal Amount { get; set; }
}
private void DelEmp()
{
if (abort)
return;
else
{
int selectedRows = dgv1.Rows.GetRowCount(DataGridViewElementStates.Selected);
for (int i = 0; i < selectedRows; ++i)
{
int id = Convert.ToInt32(dgv1.SelectedRows[i].Cells[0].Value);
var emp = empSalDB.Employees.Single(e => e.EmployeeId == id);
if (emp != null)
{
empSalDB.Employees.Remove(emp);
empSalDB.SaveChanges();
}
}
}
}
private void DelSal()
{
if (abort)
return;
else
{
int selectedRows = dgv1.Rows.GetRowCount(DataGridViewElementStates.Selected);
for (int i = 0; i < selectedRows; ++i)
{
int id = Convert.ToInt32(dgv1.SelectedRows[i].Cells[0].Value);
var sal = empSalDB.Salaries.Single(s => s.SalaryId == id);
if (sal != null)
{
empSalDB.Salaries.Remove(sal);
empSalDB.SaveChanges();
}
}
}
}
Upvotes: 0
Views: 84
Reputation: 2565
You need to to mark Employee's SalaryId as nullable. If its not nullable, what happens when you delete a Salary? The related Employee's SalaryId can't be set to the deleted Salary's Id because it doesn't exist but you cant leave the Id null. Salary is optional to an Employee so reflect that by allowing it to be null.
public class Employee
{
...
public int? SalaryId { get; set; }
}
Alternatively, you can turn on CascadeDelete using the Fluent API's WillCascadeOnDelete(true)
.
Upvotes: 1