1

I am facing an issue: we have an ASP.NET Core 2.2 Web API project with EF Core 2.2. We are using default IOC framework to create the DbContext with scope lifetime. And we have a socket pipeline connected to our ASP.NET Web API service.

I find that when we change the data in the web frontend, the socket pipeline will always get the old result (we are using .FirstOrDefault() to fetch the data, it should not be the problem with first-level cache).

So I infer that it might be because of that the scope lifetime for DbContext, so I changed it to transient lifetime. And it works! We get the modified record.

I have two questions:

  1. Is that behavior of DbContext by design? Or maybe I have some tricky issue in my code.
  2. How much performance will the transient lifetime DbContext cost? Since maybe I will make every DbContext transient
1
  • Creating a new DbContext is not expensive at all: About the other issues that you have, I don't understand what you mean. Commented Jul 5, 2019 at 11:09

1 Answer 1

1

1) Is that behavior of DbContext by design?

Yes

For each item in the result set If this is a tracking query, EF checks if the data represents an entity already in the change tracker for the context instance If so, the existing entity is returned If not, a new entity is created, change tracking is setup, and the new entity is returned

How Queries Work

2) How much performance will the transient lifetime DbContext cost?

Very little. Especially in ASP.NET Core, which has DbContext Pooling

Since maybe I will make every DbContext transient

But you shouldn't do that. Using a request-scoped DbContext is very useful. For instance you can use the DbContext in various layers of your application without having to pass one around, and you can manage transactions more easily.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks,David! So I still use the Scoped Lifetime , but change the Get method to be a no tracking Method. Could you give some suggestion?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.