[c#] Entity Framework Core: A second operation started on this context before a previous operation completed

I'm working on a ASP.Net Core 2.0 project using Entity Framework Core

<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.1" />
  <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.0"/>

And in one of my list methods I'm getting this error:

InvalidOperationException: A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.

This is my method:

    public ListResponseVM<ClientVM> GetClients([FromRoute] int currentPage, int pageSize, string search)
        var resp = new ListResponseVM<ClientVM>();
        var items = _context.Clients
            .Include(i => i.Contacts)
            .Include(i => i.Addresses)
            .Include(i => i.Urls)
            .Include(i => i.Users)
            .Where(p => string.IsNullOrEmpty(search) || p.CompanyName.Contains(search))
            .OrderBy(p => p.CompanyName)
            .ToPagedList(pageSize, currentPage);

        resp.NumberOfPages = items.TotalPage;

        foreach (var item in items)
            var client = _mapper.Map<ClientVM>(item);

            client.Addresses = new List<AddressVM>();
            foreach (var addr in item.Addresses)
                var address = _mapper.Map<AddressVM>(addr);
                address.CountryCode = addr.CountryId;

            client.Contacts = item.Contacts.Select(p => _mapper.Map<ContactVM>(p)).ToList();
            client.Urls = item.Urls.Select(p => _mapper.Map<ClientUrlVM>(p)).ToList();
            client.Objectives = item.Objectives.Select(p => _mapper.Map<ObjectiveVM>(p)).ToList();

        return resp;

I'm a bit lost especially because it works when I run it locally, but when I deploy to my staging server (IIS 8.5) it gets me this error and it was working normally. The error started to appear after I increase the max length of one of my models. I also updated the max length of the corresponding View Model. And there are many other list methods that are very similar and they are working.

I had a Hangfire job running, but this job doesn't use the same entity. That's all I can think to be relevant. Any ideas of what could be causing this?

This question is related to c# entity-framework asp.net-web-api

The answer is

I am not sure if you are using IoC and Dependency Injection to resolve your DbContext where ever it might be used. If you do and you are using native IoC from .NET Core (or any other IoC-Container) and you are getting this error, make sure to register your DbContext as Transient. Do




instead of


AddDbContext adds the context as scoped, which might cause troubles when working with multiple threads.

Also async / await operations can cause this behaviour, when using async lambda expressions.

Adding it as transient also has its downsides. You will not be able to make changes to some entity over multiple classes that are using the context because each class will get its own instance of your DbContext.

The simple explanation for that is, that the DbContext implementation is not thread-safe. You can read more about this here

In some cases, this error occurs when calling an async method without the await keyword, which can simply be solved by adding await before the method call. however, the answer might not be related to the mentioned question but it can help solving a similar error.

The exception means that _context is being used by two threads at the same time; either two threads in the same request, or by two requests.

Is your _context declared static maybe? It should not be.

Or are you calling GetClients multiple times in the same request from somewhere else in your code?

You may already be doing this, but ideally, you'd be using dependency injection for your DbContext, which means you'll be using AddDbContext() in your Startup.cs, and your controller constructor will look something like this:

private readonly MyDbContext _context; //not static

public MyController(MyDbContext context) {
    _context = context;

If your code is not like this, show us and maybe we can help further.

  • Solve my problem using this line of code in my Startup.cs file.
    Adding a transient service means that each time the service is requested, a new instance is created when you are working with Dependency injection

           services.AddDbContext<Context>(options =>

I had the same problem and it turned out that parent service was a singelton. So the context automatically became singelton too. Even though was declared as Per Life Time Scoped in DI.

Injecting service with different lifetimes into another

  1. Never inject Scoped & Transient services into Singleton service. ( This effectively converts the transient or scoped service into the singleton. )

  2. Never inject Transient services into scoped service ( This converts the transient service into the scoped. )

I think this answer still can help some one and save many times. I solved a similar issue by changing IQueryable to List(or to array, collection...).

For example:

var list=_context.table1.where(...);


var list=_context.table1.where(...).ToList(); //or ToArray()...

I had the same error. It happened because I called a method that was constructed as public async void ... instead of public async Task ....

My situation is different: I was trying to seed the database with 30 users, belonging to specific roles, so I was running this code:

for (var i = 1; i <= 30; i++)
    CreateUserWithRole("Analyst", $"analyst{i}", UserManager);

This was a Sync function. Inside of it I had 3 calls to:

UserManager.CreateAsync(user, pass).Result
UserManager.AddToRoleAsync(user, roleName).Result

When I replaced .Result with .GetAwaiter().GetResult(), this error went away.

Entity Framework Core does not support multiple parallel operations being run on the same DbContext instance. This includes both parallel execution of async queries and any explicit concurrent use from multiple threads. Therefore, always await async calls immediately, or use separate DbContext instances for operations that execute in parallel.

I faced the same issue but the reason was none of the ones listed above. I created a task, created a scope inside the task and asked the container to obtain a service. That worked fine but then I used a second service inside the task and I forgot to also asked for it to the new scope. Because of that, the 2nd service was using a DbContext that was already disposed.

Task task = Task.Run(() =>
        using (var scope = serviceScopeFactory.CreateScope())
            var otherOfferService = scope.ServiceProvider.GetService<IOfferService>();
            // everything was ok here. then I did: 
            productService.DoSomething(); // (from the main scope) and this failed because the db context associated to that service was already disposed.

I should have done this:

var otherProductService = scope.ServiceProvider.GetService<IProductService>();

First, upvote (at the least) alsami's answer. That got me on the right path.

But for those of you doing IoC, here is a little bit of a deeper dive.

My error (same as others)

One or more errors occurred. (A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.)

My code setup. "Just the basics"...

public class MyCoolDbContext: DbContext{
    public DbSet <MySpecialObject> MySpecialObjects {        get;        set;    }


public interface IMySpecialObjectDomainData{}

and (note MyCoolDbContext is being injected)

public class MySpecialObjectEntityFrameworkDomainDataLayer: IMySpecialObjectDomainData{
    public MySpecialObjectEntityFrameworkDomainDataLayer(MyCoolDbContext context) {
        this.entityDbContext = context ?? throw new ArgumentNullException("MyCoolDbContext is null", (Exception)null);


public interface IMySpecialObjectManager{}


public class MySpecialObjectManager: IMySpecialObjectManager
    public const string ErrorMessageIMySpecialObjectDomainDataIsNull = "IMySpecialObjectDomainData is null";
    private readonly IMySpecialObjectDomainData mySpecialObjectDomainData;

    public MySpecialObjectManager(IMySpecialObjectDomainData mySpecialObjectDomainData) {
        this.mySpecialObjectDomainData = mySpecialObjectDomainData ?? throw new ArgumentNullException(ErrorMessageIMySpecialObjectDomainDataIsNull, (Exception)null);

And finally , my multi threaded class, being called from a Console App(Command Line Interface app)

    public interface IMySpecialObjectThatSpawnsThreads{}


public class MySpecialObjectThatSpawnsThreads: IMySpecialObjectThatSpawnsThreads
    public const string ErrorMessageIMySpecialObjectManagerIsNull = "IMySpecialObjectManager is null";

    private readonly IMySpecialObjectManager mySpecialObjectManager;

    public MySpecialObjectThatSpawnsThreads(IMySpecialObjectManager mySpecialObjectManager) {
        this.mySpecialObjectManager = mySpecialObjectManager ?? throw new ArgumentNullException(ErrorMessageIMySpecialObjectManagerIsNull, (Exception)null);

and the DI buildup. (Again, this is for a console application (command line interface)...which exhibits slight different behavior than web-apps)

private static IServiceProvider BuildDi(IConfiguration configuration) {
    /* this is being called early inside my command line application ("console application") */

    string defaultConnectionStringValue = string.Empty; /* get this value from configuration */

    ////setup our DI
    IServiceCollection servColl = new ServiceCollection()
        ////.AddLogging(loggingBuilder => loggingBuilder.AddConsole())

        .AddTransient<IMySpecialObjectDomainData, MySpecialObjectEntityFrameworkDomainDataLayer>()
    .AddTransient<IMySpecialObjectManager, MySpecialObjectManager>()

    /* so the "ServiceLifetime.Transient" below................is what you will find most commonly on the internet search results */
     # if (MY_ORACLE)
        .AddDbContext<ProvisioningDbContext>(options => options.UseOracle(defaultConnectionStringValue), ServiceLifetime.Transient);
     # endif

     # if (MY_SQL_SERVER)
        .AddDbContext<ProvisioningDbContext>(options => options.UseSqlServer(defaultConnectionStringValue), ServiceLifetime.Transient);
     # endif

    servColl.AddSingleton <IMySpecialObjectThatSpawnsThreads,        MySpecialObjectThatSpawnsThreads>();

    ServiceProvider servProv = servColl.BuildServiceProvider();

    return servProv;

The ones that surprised me were the (change to) transient for

        .AddTransient<IMySpecialObjectDomainData, MySpecialObjectEntityFrameworkDomainDataLayer>()
    .AddTransient<IMySpecialObjectManager, MySpecialObjectManager>()

Note, I think because IMySpecialObjectManager was being injected into "MySpecialObjectThatSpawnsThreads", those injected objects needed to be Transient to complete the chain.

The point being.......it wasn't just the (My)DbContext that needed .Transient...but a bigger chunk of the DI Graph.

Debugging Tip:

This line:

this.entityDbContext = context ?? throw new ArgumentNullException("MyCoolDbContext is null", (Exception)null);

Put your debugger break point there. If your MySpecialObjectThatSpawnsThreads is making N number of threads (say 10 threads for example)......and that line is only being hit once...that's your issue. Your DbContext is crossing threads.


I would suggest reading this below url/article (oldie but goodie) about the differences web-apps and console-apps


Here is the header of the article in case the link changes.


I hit this issue with WorkFlowCore https://github.com/danielgerlag/workflow-core

    <PackageReference Include="WorkflowCore" Version="3.1.5" />

sample code below.. to help future internet searchers

 namespace MyCompany.Proofs.WorkFlowCoreProof.BusinessLayer.Workflows.MySpecialObjectInterview.Workflows
        using System;
        using MyCompany.Proofs.WorkFlowCoreProof.BusinessLayer.Workflows.MySpecialObjectInterview.Constants;
        using MyCompany.Proofs.WorkFlowCoreProof.BusinessLayer.Workflows.MySpecialObjectInterview.Glue;
        using MyCompany.Proofs.WorkFlowCoreProof.BusinessLayer.Workflows.WorkflowSteps;

        using WorkflowCore.Interface;
        using WorkflowCore.Models;

        public class MySpecialObjectInterviewDefaultWorkflow : IWorkflow<MySpecialObjectInterviewPassThroughData>
            public const string WorkFlowId = "MySpecialObjectInterviewWorkflowId";

            public const int WorkFlowVersion = 1;

            public string Id => WorkFlowId;

            public int Version => WorkFlowVersion;

            public void Build(IWorkflowBuilder<MySpecialObjectInterviewPassThroughData> builder)
                             .StartWith(context =>
                        Console.WriteLine("Starting workflow...");
                        return ExecutionResult.Next();

                        /* bunch of other Steps here that were using IMySpecialObjectManager.. here is where my DbContext was getting cross-threaded */

                    .Then(lastContext =>

                        bool wroteConcreteMsg = false;
                        if (null != lastContext && null != lastContext.Workflow && null != lastContext.Workflow.Data)
                            MySpecialObjectInterviewPassThroughData castItem = lastContext.Workflow.Data as MySpecialObjectInterviewPassThroughData;
                            if (null != castItem)
                                Console.WriteLine("MySpecialObjectInterviewDefaultWorkflow complete :)  {0}   -> {1}", castItem.PropertyOne, castItem.PropertyTwo);
                                wroteConcreteMsg = true;

                        if (!wroteConcreteMsg)
                            Console.WriteLine("MySpecialObjectInterviewDefaultWorkflow complete (.Data did not cast)");

                        return ExecutionResult.Next();

                    .OnError(WorkflowCore.Models.WorkflowErrorHandling.Retry, TimeSpan.FromSeconds(60));



ICollection<string> workFlowGeneratedIds = new List<string>();
                for (int i = 0; i < 10; i++)
                    MySpecialObjectInterviewPassThroughData currentMySpecialObjectInterviewPassThroughData = new MySpecialObjectInterviewPassThroughData();
                    currentMySpecialObjectInterviewPassThroughData.MySpecialObjectInterviewPassThroughDataSurrogateKey = i;

                    ////  private readonly IWorkflowHost workflowHost;
                    string wfid = await this.workflowHost.StartWorkflow(MySpecialObjectInterviewDefaultWorkflow.WorkFlowId, MySpecialObjectInterviewDefaultWorkflow.WorkFlowVersion, currentMySpecialObjectInterviewPassThroughData);

I have a background service that performs an action for each entry in a table. The problem is, that if I iterate over and modify some data all on the same instance of the DbContext this error occurs.

One solution, as mentioned in this thread is to change the DbContext's lifetime to transient by defining it like


but because I do changes in multiple different services and commit them at once using the SaveChanges() method this solution doesnt work in my case.

Because my code runs in a service, I was doing something like

using (var scope = Services.CreateScope())
   var entities = scope.ServiceProvider.GetRequiredService<IReadService>().GetEntities();
   var writeService = scope.ServiceProvider.GetRequiredService<IWriteService>();
   foreach (Entity entity in entities)

to be able to use the service like if it was a simple request. So to solve the issue i just split the single scope into two, one for the query and the other for the write operations like so:

using (var readScope = Services.CreateScope())
using (var writeScope = Services.CreateScope())
   var entities = readScope.ServiceProvider.GetRequiredService<IReadService>().GetEntities();
   var writeService = writeScope.ServiceProvider.GetRequiredService<IWriteService>();
   foreach (Entity entity in entities)

Like that, there are effevtively two different instances of the DbContext being used.

Another possible solution would be to make sure, that the read operation has terminated before starting the iteration. That is not very pratical in my case because there could be a lot of results that would all need to be loaded into memory for the operation which I tried to avoid by using a Queryable in the first place.

Another possible case: if you use the connection direct, don't forget to close if. I needed to execute arbitrary SQL query, and read the result. This was a quick fix, I did not want to define a data class, not set up "normal" SQL connection. So simply I reused EFC's database connection as var connection = Context.Database.GetDbConnection() as SqlConnection. Make sure you call connection.Close() before you do Context.SaveChanges().

I know this issue has been asked two years ago, but I just had this issue and the fix I used really helped.

If you are doing two queries with the same Context - you might need to remove the AsNoTracking. If you do use AsNoTracking you are creating a new data-reader for each read. Two data readers cannot read the same data.

In my case I use a template component in Blazor.

 <BTable ID="Table1" TotalRows="MyList.Count()">

The problem is calling a method (Count) in the component header. To resolve the problem I changed it like this :

int total = MyList.Count();

and later :

<BTable ID="Table1" TotalRows="total">

In my case I was using a lock which does not allow the use of await and does not create compiler warning when you don't await an async.

The problem:

lock (someLockObject) {
    // do stuff

// some other code somewhere else doing await context.SaveChangesAsync() shortly after the lock gets the concurrency error

The fix: Wait for the async inside the lock by making it blocking with a .Wait()

lock (someLockObject) {
    // do stuff

I managed to get that error by passing an IQueryable into a method that then used that IQueryable 'list' as part of a another query to the same context.

public void FirstMethod()
    // This is returning an IQueryable
    var stockItems = _dbContext.StockItems
        .Where(st => st.IsSomething);


public void SecondMethod(IEnumerable<Stock> stockItems)
    var grnTrans = _dbContext.InvoiceLines
        .Where(il => stockItems.Contains(il.StockItem))

To stop that happening I used the approach here and materialised that list before passing it the second method, by changing the call to SecondMethod to be SecondMethod(stockItems.ToList()

I got the same problem when I try to use FirstOrDefaultAsync() in the async method in the code below. And when I fixed FirstOrDefault() - the problem was solved!

        await _context.SaveChangesAsync();

        int userId = _context.Users
            .Where(u => u.UserName == Options.UserName)

I got the same message. But it's not making any sense in my case. My issue is I used a "NotMapped" property by mistake. It probably only means an error of Linq syntax or model class in some cases. The error message seems misleading. The original meaning of this message is you can't call async on same dbcontext more than once in the same request.

public int PostId { get; set; }
public virtual Post Post { get; set; }

You can check this link for detail, https://www.softwareblogs.com/Posts/Details/5/error-a-second-operation-started-on-this-context-before-a-previous-operation-completed

you can use SemaphoreSlim to block the next thread that will try to execute that EF call.

static SemaphoreSlim semSlim = new SemaphoreSlim(1, 1);

await semSlim.WaitAsync();
  // something like this here...
  // EmployeeService.GetList(); or...
  var result = await _ctx.Employees.ToListAsync();

If your method is returning something back, you can solve this error by putting .Result to the end of the job and .Wait() if it doesn't return anything.

I just managed to make it work again. It makes not much sense but it worked:

  1. Remove Hangfire from StartUp (I was creating my job there)
  2. Deleted the hangfire database
  3. Restarted the server

I'll investigate further later but the method I called with hangfire receives a DBContext and that is the possible cause.

Questions with c# tag:

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array How can I add raw data body to an axios request? Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file Convert string to boolean in C# Entity Framework Core: A second operation started on this context before a previous operation completed ASP.NET Core - Swashbuckle not creating swagger.json file Is ConfigurationManager.AppSettings available in .NET Core 2.0? No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization Getting value from appsettings.json in .net core .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Automatically set appsettings.json for dev and release environments in asp.net core? How to use log4net in Asp.net core 2.0 Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App Unable to create migrations after upgrading to ASP.NET Core 2.0 Update .NET web service to use TLS 1.2 Using app.config in .Net Core How to send json data in POST request using C# ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response How to enable CORS in ASP.net Core WebAPI VS 2017 Metadata file '.dll could not be found How to set combobox default value? How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac ALTER TABLE DROP COLUMN failed because one or more objects access this column Error: the entity type requires a primary key How to POST using HTTPclient content type = application/x-www-form-urlencoded CORS: credentials mode is 'include' Visual Studio 2017: Display method references Where is NuGet.Config file located in Visual Studio project? Unity Scripts edited in Visual studio don't provide autocomplete How to create roles in ASP.NET Core and assign them to users? Return file in ASP.Net Core Web API ASP.NET Core return JSON with status code auto create database in Entity Framework Core Class Diagrams in VS 2017 How to read/write files in .Net Core? How to read values from the querystring with ASP.NET Core? how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application? ASP.NET Core Get Json Array using IConfiguration Entity Framework Core add unique constraint code-first No templates in Visual Studio 2017 ps1 cannot be loaded because running scripts is disabled on this system

Questions with entity-framework tag:

Entity Framework Core: A second operation started on this context before a previous operation completed EF Core add-migration Build Failed Entity Framework Core add unique constraint code-first 'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked Auto-increment on partial primary key with Entity Framework Core Working with SQL views in Entity Framework Core How can I make my string property nullable? Lazy Loading vs Eager Loading How to add/update child entities when updating a parent entity in EF Entity Framework Queryable async There is already an object named in the database How to update record using Entity Framework 6? Save and retrieve image (binary) from SQL Server using Entity Framework 6 Entity Framework - "An error occurred while updating the entries. See the inner exception for details" ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls lambda expression join multiple tables with select and where clause How are people unit testing with Entity Framework 6, should you bother? Entity Framework rollback and remove bad migration The model backing the 'ApplicationDbContext' context has changed since the database was created Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient' Update Multiple Rows in Entity Framework from a list of ids Setting unique Constraint with fluent API? Entity Framework Join 3 Tables using stored procedure in entity framework Entity Framework code-first: migration fails with update-database, forces unneccessary(?) add-migration How to call Stored Procedure in Entity Framework 6 (Code-First)? Update records using LINQ Entity Framework - Code First - Can't Store List<String> The entity type <type> is not part of the model for the current context How to check model string property for null in a razor view How to re-create database for Entity Framework? Entity Framework Refresh context? Entity Framework change connection at runtime EntityType has no key defined error ASP.NET Identity DbContext confusion Mapping composite keys using EF code first Entity Framework 6 Code first Default value Select multiple columns using Entity Framework The object 'DF__*' is dependent on column '*' - Changing int to double LEFT JOIN in LINQ to entities? Unable to create a constant value of type Only primitive types or enumeration types are supported in this context Unique Key constraints for multiple columns in Entity Framework No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient' Solving "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection" InvalidOperationException Entity Framework The underlying provider failed on Open Entity Framework .Remove() vs. .DeleteObject() Delete a single record from Entity Framework? The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

Questions with asp.net-web-api tag:

Entity Framework Core: A second operation started on this context before a previous operation completed FromBody string parameter is giving null How to read request body in an asp.net core webapi controller? JWT authentication for ASP.NET Web API Token based authentication in Web API without any user interface Web API optional parameters How do I get the raw request body from the Request.Content object using .net 4 api endpoint How to use a client certificate to authenticate and authorize in a Web API HTTP 415 unsupported media type error when calling Web API 2 endpoint The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located Effectively use async/await with ASP.NET Web API Java finished with non-zero exit value 2 - Android Gradle Calling Web API from MVC controller Getting "error": "unsupported_grant_type" when trying to get a JWT by calling an OWIN OAuth secured Web Api via Postman What exactly is the difference between Web API and REST API in MVC? Return content with IHttpActionResult for non-OK response How to set up a Web API controller for multipart/form-data MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource How to add/update child entities when updating a parent entity in EF Return HTML from ASP.NET Web API Postman: sending nested JSON object How to return a file (FileContentResult) in ASP.NET WebAPI Return JsonResult from web api without its properties Pass multiple complex objects to a post/put Web API method Why do we have to specify FromBody and FromUri? How to update a claim in ASP.NET Identity? Make sure that the controller has a parameterless public constructor error Download file from an ASP.NET Web API method using AngularJS Failed to serialize the response in Web API with Json Optional Parameters in Web Api Attribute Routing web-api POST body object always null Asp Net Web API 2.1 get client IP address Error sending json in POST to web API service The 'Access-Control-Allow-Origin' header contains multiple values Make Https call using HttpClient Why should I use IHttpActionResult instead of HttpResponseMessage? Get the current user, within an ApiController action, without passing the userID as a parameter How to add and get Header values in WebApi OWIN Security - How to Implement OAuth2 Refresh Tokens Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN' download csv file from web api in angular js GlobalConfiguration.Configure() not present after Web API 2 and .NET 4.5.1 migration How to pass json POST data to Web API method as an object? Entity Framework change connection at runtime HTTP Error 500.19 and error code : 0x80070021 How to get base URL in Web API controller? Select All distinct values in a column using LINQ Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013 Entity framework self referencing loop detected How to consume a webApi from asp.net Web API to store result in database?