Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Scaffolding Issue

When I try to Scaffold My Controller, the page throws following error

"Unable to retrieve metadata for 'Entity.Observation'. No parameterless constructor defined for this object."

Can you help me this?

Here is the code:

 public class Observation
    {
        public Observation() { }

        public virtual int Id { get; set; }
        public virtual DateTime Date { get; set; }
        public virtual User Teacher { get; set; }
        public virtual User Observer { get; set; }
        public virtual AcademicYear AcademicYear { get; set; }
    }

Entities is in other project, Context is in different project and Controllers and Views are in same project

I am using Entity Framework Code First model

like image 218
anwar Avatar asked Aug 17 '11 19:08

anwar


3 Answers

I had the exactly same problem, the error stated that a default (parameterless) constructor was missing from my model. In my case the error was misleading - my model did in fact contain a default constructor but my DataContext did not. I added a default constructor to my DataContext - problem solved!

public class ReportEntities : DbContext
    {

    public ReportEntities():base()
        {

        }

    public ReportEntities(string connection)
        : base(connection)
        {

        }

    ...
     }
like image 127
The Ed R Avatar answered Oct 21 '22 21:10

The Ed R


I had the same problem. Here's how I fixed -

  1. First, I added another constructor with no parameter to the context class (not the model class).

  2. After that I had to rebuild the project. Really important because the tooling reads the meta data (i burned 10 miuntes before I realized I had to do this).

Once I did those two things, I was able to add the controller and views with no problem.

like image 24
Harry Mower Avatar answered Oct 21 '22 22:10

Harry Mower


If you have you EF models in a separate project you can try right clicking the edmx file and "Add Code Generation Items" and choose "DbContext Generator". This is available only if you have EF 4.1 (easiest way to install is to use NuGet). See if that helps. Every time I make a change to my model project I generally make sure i build that project before I start working on the other projects.

like image 33
mithun_daa Avatar answered Oct 21 '22 21:10

mithun_daa