Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 & model, I get an alert saying "Object reference not set to an instance of an object".

I've done a bit of searching and found that some causes are incorrect project type Guids in the .csproj file, incomplete installation of the MvcScaffolding nuget package and one suggestion of installing Powershell 3.

I have made sure all my project type guids are correct, made sure the MvcScaffolding package is installed correctly, and I've even installed Powershell 3.

None of this has solved the problem for me. All I can think is there is a problem with my data context/model although it created the tables/relationships fine. Code below:

Context:

public class PropertySearchContext : DbContext 
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Property>().HasRequired(p => p.Office).WithMany(o => o.Properties).HasForeignKey(p => p.OfficeId);
    }

    public DbSet<Office> Offices { get; set; }
    public DbSet<Property> Properties { get; set; } 
}

Model:

[Serializable]
public class Property
{
    public int PropertyId { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string Town { get; set; }
    public string County { get; set; }
    public string Postcode { get; set; }

    public int Bedrooms { get; set; }
    public int Bathrooms { get; set; }

    public string UmbracoNodeId { get; set; }
    public string MainImageUrl { get; set; }
    public string ListingImageUrl { get; set; }
    public int TotalImageCount { get; set; }
    public PropertyType PropertyType { get; set; }
    public PropertyStatus PropertyStatus { get; set; }
    public long Price { get; set; }
    public string ListingUrl { get; set; }

    //Navigation Properties
    public int OfficeId { get; set; }
    public virtual Office Office { get; set; }

    //Meta properties
    public DateTime CreatedAt { get; set; }
    public string CreatedBy { get; set; }
    public DateTime UpdatedAt { get; set; }
    public string UpdatedBy { get; set; }
}

Connection String:

<add name="PropertySearchContext" connectionString="Data Source=MERCURY\SQLEXPRESS;Initial Catalog=DATABASE_NAME;Integrated Security=False;User ID=dbFakeUser;Password=fakePassword;Connect Timeout=10" providerName="System.Data.SqlClient" />

Any help with this would be greatly appreciated as I've tried every suggestion and I still can't create a controller with scaffolding. Driving me mad!

Thanks!

like image 439
JustinMoser Avatar asked Jun 08 '13 22:06

JustinMoser


2 Answers

Found the problem. In my model, I had a property with a custom enum type, which was in my business project. In my service project, I had my data model project referenced but not the business project. So adding a reference to the model AND business project allowed me to add scaffold controllers fine.

Seems obvious I know, but the error message it gives you is so unhelpful!

Anyway, I hope this helps anyone having the same problem, and can't fix it using the other suggestions.

like image 172
JustinMoser Avatar answered Nov 02 '22 16:11

JustinMoser


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:

  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DATABASE_NAME.mdf;Initial Catalog=DATABASE_NAME;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="PropertySearchContext" connectionString="Data Source=MERCURY\SQLEXPRESS;Initial Catalog=DATABASE_NAME;Integrated Security=False;User ID=dbFakeUser;Password=fakePassword;Connect Timeout=10" providerName="System.Data.SqlClient" />
  </connectionStrings>

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.

like image 44
Gobe Avatar answered Nov 02 '22 15:11

Gobe