“Object reference not set to an instance of an object” when creating a new Web API controller with EF Scaffolding in Visual Studio 2012

后端 未结 5 1389
春和景丽
春和景丽 2021-01-18 16:42

I have an MVC4/Web API project, with an Entity Framework, Code First data model. When I try to create a new API Controller with read/write methods using a data context &

5条回答
  •  南笙
    南笙 (楼主)
    2021-01-18 17:37

    I am adding an answer as my problem was the same and my solution was different. It had no relation to the referenced assemblies. First of all, I believe it only happened because the Web API project had just been created (from scratch).

    I will give you some code examples based on the OP code. First, my context class that inherits from DbContext had to call the base constructor passing as argument the connection string name:

    public class PropertySearchContext : DbContext 
    {
        public PropertySearchContext () : base("name=PropertySearchContext")
    

    Second, the Web API application would internally look inside Web.config for a connection string named PropertySearchContext. Web.config already comes with a DefaultConnection, so I just had to add a new one with the proper name and settings:

      
        
        
      
    

    note: the OQ already has that connection string.

    Third and finally, I had to build the WebAPI project. Once successful, the creation of controllers worked fine.

提交回复
热议问题