Will Entity Framework and SQL Server lock a object

2019-08-26 02:08发布

I am deleting some objects and rows using two methods inside my asp.net MVC web application: first approach includes deleting an Entity Framework object, such as:

public void DeleteMyObject(MyObject a)
{
    entities1.MyObject.Remove(a);
}

while the second approach is calling a stored procedure from my repository method to delete a database row such as:

public void Deleteuserclass(string a, int u)
{
     entities1.deleteuserclass(a, u); 
}

which calls the following stored procedure:

ALTER PROCEDURE dbo.deleteuserclass
    @userid nvarchar(50),
    @classid int
AS
Begin
    Delete from Users_Classes where UserID = @userid  AND ClassID = @classid

    if @@rowcount = 0     
        Raiserror('No record deleted',1,16) 
END

Using any of the above two approaches; can I be confident that if two delete requests for deleting the same object arrive at the server at the same time, then only one request will delete the record from the database and the other request will receive an exception (I mean will the Entity Framework or the SQL Server database lock the row while it is being deleted ?)?

BR

1条回答
对你真心纯属浪费
2楼-- · 2019-08-26 02:39

One or the other will execute first.

If your stored procedure is execured second you will get an exception due to the if statement in the stored procedure.

If the EF command is executed second there will be a OptimisticConcurrencyException, see: EF eqivalent for rows affected of SqlCommand.ExecuteNonQuery

查看更多
登录 后发表回答