Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC add controller error

Tags:

asp.net-mvc

When I try to add a 'MOVIES" controller, it errors: "There was an error generating 'MvcMovieSF.Models.MovieDBContext. Try rebuilding your project."

I have rebuilt the project and it continues to error. Thanks in advance!

namespace MvcMovieSF.Models
{
    public class Movie
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public DateTime ReleaseDate { get; set; }
        public string Genre { get; set; }
        public decimal Price { get; set; }
    }

    public class MovieDBContext : DbContext
    {
        public DbSet Movies { get; set; }
    }
}

JUST NOTICED: I'm not sitting at my own computer and I noticed SQLExpress services were not started; I don't have permission on this computer to start the service. Could that be the reason?

like image 446
Susan Avatar asked Jan 19 '23 21:01

Susan


1 Answers

Adding a controller also modifies your context class. If you have implemented partial class to add some business rules into your context, the framework cannot successfully edit your partial class to find the correct points for its own insertions.

Stupid, though, removing the business rules might help. After creating your controller, you can put them back.

(at least, this worked for me, 10 minutes ago...)

Edit:

The Context class might be partially implemented like this:

public partial class MyDatabaseEntities : DbContext
{
    public override int SaveChanges() { ... }

    #region Some Business Rules Here 
    ...
    #endregion
}

Here, if you try to add a new controller, you will fail with the error: "There was an error generating 'MyDatabaseEntities'. Try rebuilding your project." And rebuilding will not help at all...

My solution is:

  1. Remove these business rules like this, of course, keep them in a safe place, as you will probably need them afterwards:

    public partial class MyDatabaseEntities : DbContext
    {
        public override int SaveChanges() { ... }
    }
    
  2. Create your controller. You should be successful this time.

  3. Remove the codes that are added by the framework from your context class:

    public partial class MyDatabaseEntities : DbContext
    {
        public override int SaveChanges() { ... }
    
        public DbSet<MyModelClass> MyModelClass { get; set; }  // remove this line
    }
    
  4. Put the business rules back.

Hope this helps.

like image 115
Bolt Thunder Avatar answered Jan 28 '23 12:01

Bolt Thunder