0

I have a business layer, with a Order class and Item class. Suponse that I want to add a new line to the order. How the business logic has not known about the data access layer, I will use a service layer, with a method that is AddItemToOrder, something like this:

public Order AddItemToOrder(Order paramOrder, Item paramItem)
{
    //Get order from database with EF Core
    //Add item to order
    //Save changes in database.
}

Well, I some small prject, I have mixed business logic and data access logic in this way, having a method in my Order class, in the busisiness layer:

public order AddItem(Item paramItem)
{
    using (MyDbContext = new DbContext(options))
    {
        string myStrSql = "select * from Order where IDOrder = {0} with(UPDLOCK)";
        Order myOrderDb = myDbContext.Order.FromRawSql(myStrSql, 1).Include(x => x.Items).FirstOrDefault();
       //Some validations, for example number of items <= 20
       //if validations are correct
        myOrderDb.Items.Add(paramItem);
       SaveChanges();
    }

}

In this case, I can use pessimistic concurency because I am using EF directly in my business logic, but I think that it is not very correct.

the other option, in the service, I get the order first, but I can't use pessimistic concurrency becuase the dbContext is disponse after I get the data.

So I am wondering if it is possible to use pessimistic concurrency if I separate business logic layer and data access layer.

Perhaps another option it would be use optimistic concurrency, but I would like to know if it would be possible to use pessimistic concurrence, and how it would be done.

Thanks.

Álvaro García
  • 18,114
  • 30
  • 102
  • 193
  • Start transaction or open connection manually. In this case EF will not close connection. – Svyatoslav Danyliv Oct 17 '21 at 12:28
  • EF Core does not support pessimistic concurrency. You'd have to work with Database connection manually. Very much recommend optimistic concurrency approach: https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/concurrency?view=aspnetcore-5.0 – Neil W Oct 17 '21 at 12:31
  • The case you show isn't even pessimistic concurrency. The lock is gone immediately after `FirstOrDefault()`. – Gert Arnold Oct 17 '21 at 19:02

0 Answers0