0

I have read a Q&A written 9 years ago, here is the link: entity framework - Unit of Work, Repositories and IDisposable - Stack Overflow

which showed it should implement IDisposable. But other videos posted on YouTube don't. Should it implement IDisposable interface now?

How can it roll back when there is no transaction that the entities have a foreign key association?

public class Employee
{
    public long Id { get; set; }
    public string Name { get; set; }
    public long DepartmentId { get; set; }
}

public class Department
{
    public long Id { get; set; }
    public string Name { get; set; }
}

public void AddDepartmentAndEmployees()
{
    var department = new Department { Name = "Dev" };

    var employees = new List<Employee> 
    { 
       new Employee { Name = "Jack" },
       new Employee { Name = "Tim" },
    }

    _departmentRepository.Add(department);
    _departmentRepository.SaveChange();

    employees.All(e => e.DepartmentId = department.Id );
    // if there throw a unknown exception
    // and how can i roll back?
    _employeeRespository.AddRange(employees);
    _departmentRepository.SaveChange();
}

Solve the above two problems.

Sorry about my poor English, but I have try my best.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Vincent
  • 51
  • 7

1 Answers1

1

this may help you Transactions in unit of work design pattern

It's a best practice to have the UnitOfWork being disposable according to Microsoft article about UnitOfWork Design Pattern

you can use TransactionScope to create transactions and commit or roll it back if you have any problem