Reputation: 11
I have an application where multiple users can login. For that I have a kind of session object that stores a DBContext
object. But the problem is, that the cached DBContext
stores only the data of the logged user. When another user are also logged in, then the cached data is maybe older because it will be changed by the second user.
Is there a conceptional way to handle this. Instead of caching the DBContext
object, I can create it every time I do an database request. Is this the correct way or is there a kind of event to catch to know that the database content is changed?
Upvotes: 0
Views: 234
Reputation: 635
You should not be caching the DbContext object in any way. DbContext maintains state internally for multiple users automatically.
You create a new context when you open a controller to respond to a user request for data. In Entity Framework 6 this would look like
public class FeedItemController : ApiController
{
private LynxFeedAPI_Context db = new LynxFeedAPI_Context();
// GET api/FeedItem
public IQueryable<FeedItem> GetFeedItems()
{
return db.FeedItems;
}
It is done differently in EF 7 where Startup.cs is used to setup the Dependency Injection
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers.
// You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json.
// services.AddWebApiConventions();
services.Configure<AppSettings>(configuration.GetConfigurationSection("AppSettings"));
// Add EF services to the services container.
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(configuration["Data:DefaultConnection:ConnectionString"]));
services.AddSingleton<IApplicationDbContext, ApplicationDbContext>();
services.AddSingleton<IProposalDataRepository, ProposalDataRepository>();
services.AddSingleton<IPositionDataRepository, PositionDataRepository>();
services.AddSingleton<IMandatoryReqDataRepository, MandatoryReqDataRepository>();
services.AddSingleton<IRatedReqDataRepository, RatedReqDataRepository>();
}
and is used by the controller
public class ProposalController : Controller
{
private readonly IProposalDataRepository repProposal;
public ProposalController(IProposalDataRepository repository) {
repProposal = repository;
}
[HttpGet]
public IEnumerable<Proposal> GetAll()
{
return repProposal.SelectAll();
}
where it is not necessary to ever make a call to create a new DbContext
Upvotes: 2