问题
Below are my 2 class sharing 1 to many relationship :
public partial class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Skills> Skills { get; set; }
}
public partial class Skills
{
public int Id { get; set; }
public Nullable<int> EmployeeId { get; set; }
public string Skills { get; set; }
public virtual Employee Employee { get; set; }
}
Now I am trying to remove employees with its corresponding skills in following way :
1) Deleting both employee and skills in 1 method with only save changes. I guess I will be having performance benefit in this case as I need to call save changes only once but there is also 1 issue that if skills got deleted but if error occurs while deleting employee in that case I will lose Skills of corresponding Employee.
public void Delete(int[] ids)
{
using (var context = new MyEntities())
{
context.Skills.RemoveRange(context.Skills.Where(cd => ids.Contains(cd.EmployeeId)));
context.Employee.RemoveRange(context.Employee.Where(t => ids.Contains(t.Id)));
context.SaveChanges();
}
}
2) Another option is to use transaction to make sure that both and child gets deleted successfully like below :
public HttpResponseMessage Delete(int[] ids)
{
using (var context = new MyEntities())
{
using (var transaction = context.Database.BeginTransaction())
{
try
{
DeleteSkills(ids,context);
DeleteEmployees(ids,context);
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
// throw exception.
}
}
}
}
public void DeleteEmployees(int[] ids,MyEntities _context)
{
_context.Employee.RemoveRange(_context.Employee.Where(t => ids.Contains(t.Id)));
_context.SaveChanges();
}
public void DeleteSkills(int[] ids, MyEntities _context)
{
_context.Skills.RemoveRange(_context.Skills.Where(cd => ids.Contains(cd.EmployeeId)));
_context.SaveChanges();
}
3) I am looking for an option where I don't need to remove child (Skills) explicitly and child gets removed automatically based on removal of parent (Employee) entity like the way it happens in case of Code first Cascade on delete so that I don't have to fire 2 queries to remove parent and child (my first option) or I don't have to maintain transaction (my second option.)
I did some research but couldn't find any help on removing child automatically based on removal of parent in case of Database first approach (.edmx).
What is an efficient way to handle this scenario?
来源:https://stackoverflow.com/questions/46450952/how-to-delete-child-automatically-based-on-parent-deletion-for-database-first-ap