G. Stoynev
G. Stoynev

Reputation: 7783

Database.SqlQuery thread safety

Does anybody know if Database.SqlQuery does something under the hood that would make it thread-unsafe (like creating or enlisting a transaction, etc.)?

This is the piece of code that I have to call from multiple threads - the query is very straight-forward, hardcoded (no access to shared user-code data):

public virtual long GetId(string sql)
{
    var newid = DbContext.Database.SqlQuery<long>(sql).First();
    return newid;
}

My goal is to get by during a minor release - then we will have a chance to properly implement synchronization if needed.

Upvotes: 4

Views: 455

Answers (1)

Bas
Bas

Reputation: 27105

Since ADO.NET employs connection pooling and creating a new DbContext is relatively light-weight, you are safe to create a lot of contexts which can be disposed after using them.

So I would consider creating a new DbContext in a using block instead of using the field/property.

To answer your first question, running a query like the code in your question will only execute the statement against the database, as you would do in an old fashioned ADO.NET way.

Upvotes: 1

Related Questions