ASP.Net MVC add controller error - 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?

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:
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() { ... }
}
Create your controller. You should be successful this time.
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
}
Put the business rules back.
Hope this helps.

I had the same problem while adding new controller in ASP.NET MVC 4, I solved the problem by moving the Database.SetInitializer(new SomeDataContextInitializer()); from the constructor of the DBContext to Application_Start method in Global.asax.cs. Hope it helps.

#Bolt Thunder put me on the right track. In my case, the DbContext class was modified to have IDbSet for testing, which made it happen. Changed that - problem solved.

my project name was MVC and i had this class
public class download
{
public int download_id { get; set; }
public int download_category_id { get; set; }
public string download_name { get; set; }
public int download_size { get; set; }
public string download_description { get; set; }
public string download_path { get; set; }
public download_category download_category { get; set; }
}
public class download_category
{
public int download_category_id { get; set; }
public string download_category_name { get; set; }
}
public class DownloadDbContext : DbContext
{
public DbSet<download> downloads { get; set; }
public DbSet<download_category> download_categorys { get; set; }
}
and i got similar error when scaffolding(there was an error generating try rebuilding your project).
i am using visual studio 2012 version 11.0.50727.1 RTMREL and reference to entity as ...\EntityFramework.5.0.0\lib\net45\EntityFramework.dll
first i divide class into three classes (three seperate *.cs files) and also use DataAnnotations in download and download_category classes to use [key] for id columns and problem solved.
my classes were as below in Models folder :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MVC.Models;
using System.ComponentModel.DataAnnotations;
namespace MVC.Models
{
public class Download
{
[Key]
public int download_id { get; set; }
public int download_category_id { get; set; }
public string download_name { get; set; }
public int download_size { get; set; }
public string download_description { get; set; }
public string download_path { get; set; }
public Download_category download_category { get; set; }
}
}
and
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace MVC.Models
{
public class Download_category
{
[Key]
public int download_category_id { get; set; }
public string download_category_name { get; set; }
}
}
and
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MVC.Models
{
public class DownloadDbContext:DbContext
{
public DbSet<Download> downloads { get; set; }
public DbSet<Download_category> download_categorys { get; set; }
}
}

I had the same problem as Susan. In my case specifying the model type for the DbSet (public DbSet<Movie> Movies ) in the context class fixed the problem.
I am using VS 2012 and i added the Entity Framework 5.0 package to the solution.

Related

Domain classes not visible to Data layer (Application context class )

To make data-layer be aware of my domain classes, I've added a reference between the two class libraries, HMSContext (i.e., data-layer) and Hms.Entities (i.e., domain-classes).
Following is code from HMS.Entities:
namespace HMS.Entities
{
class Accomodation
{
public int ID { get; set; }
public int AccomodationPackageID { get; set; }
public AccomodationPackage AccomodationPackage { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
}
Code from HMSContext.cs:
using System.Data.Entity;
namespace HMS.Data
{
public class HMSContext : DbContext
{
public DbSet<Accomodation> Accomodations { get; set; }
}
}
I've added a reference between these two .dlls. A snapshot showing this is attached here. For some reason, HRMContext.cs is not reading HMS.Entities despite added reference. Am I missing anything? Can someone please shed light on this. Thanks in advance.
You are using using System.Data.Entity; where it is not related to your project structure. So add HMS.Entities too.
Any time you have such a problem, try using the full namespace and check if it is correct or not.
Note that you also have refactoring capabilities too. You can use ( Ctrl + . ) and Visual Studio helps you to use the correct namespace.
Your code has to be like this:
using System.Data.Entity;
using HMS.Entities;
namespace HMS.Data
{
public class HMSContext : DbContext
{
public DbSet<Accomodation> Accomodations { get; set; }
}
}
And for the Entity class you should use public keyword:
namespace HMS.Entities
{
public class Accomodation
{
public int ID { get; set; }
public int AccomodationPackageID { get; set; }
public AccomodationPackage AccomodationPackage { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
}

The type name 'Models' does not exist in the type 'Database'

I tried to create a really simple dbcontext class today with 2 classes "Class" and "Student". After I enabled-migrations the configuration file keeps saying it connot find the namespace to Models in the project Database.
ERROR CODE:
CS0426 The type name 'Models' does not exist in the type 'Database' Database C:\Users\rodney\documents\visual studio 2017\Projects\SchoolManagementProtal\Database\Migrations\Configuration.cs
Project stucture
DbContext class:
using System.Data.Entity;
namespace Database.Models
{
public class DbContext : System.Data.Entity.DbContext
{
public DbSet<Class> Classes { get; set; }
public DbSet<Student> Students { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Class>()
.HasMany(c => c.Students)
.WithMany(c => c.Classes);
}
}
}
Configuration file in migrations:
namespace Database.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<Database.**Models**.DbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
}
}
Class Entity:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Database.Models
{
public class Class
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(50)]
public string ClassName { get; set; }
[Required]
[Range(1, 100)]
public int MaxStudents { get; set; }
public int StudentId { get; set; }
public ICollection<Student> Students { get; set; }
}
}
Students Entity
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Database.Models
{
public class Student
{
[Key]
public int Id { get; set; }
public int ClassId { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
[Required]
public DateTime DateOfBirth { get; set; }
[Required]
public Gender Gender { get; set; }
[Required]
public int TotalHours { get; set; }
[Required]
public int HoursStudied { get; set; }
public DateTime DateJoined { get; set; }
public ICollection<Class> Classes { get; set; }
public int HoursLeft
{
get
{
return this.TotalHours - this.HoursStudied;
}
}
}
}
I guess I am missing some type of reference or something. but even after googling for some time I couldn't find any solution. Thanks for the help in advance. Cheers!
There is a name clash between System.Data.Entity.Database class and your Database namespace, in which case the class takes precedence, hence the compiler error.
You need to resolve it by either using the global namespace alias:
: DbMigrationsConfiguration<global::Database.Models.DbContext>
or since in this particular case the Database.Models is directly accessible from Database.Migrations, by using relative namespace reference:
: DbMigrationsConfiguration<Models.DbContext>

'System.Data.Entity.ModelConfiguration.ModelValidationException' occurred in EntityFramework.dll but was not handled in user code

I m working on an existing MVC project.When my context class inherited from DBContext everythink is fine but when i changed it to IdentityDbContext i get that error.The error occured in that line :
var makaleler = context.Makale.ToList();
my controller:
using mvcblogdeneme.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace mvcblogdeneme.Controllers
{
public class HomeController : Controller
{
// GET: Home
BlogDatabaseContext context = new BlogDatabaseContext();
public ActionResult Index()
{
return View();
}
public ActionResult CategoryWidgetGetir()
{
var kat = context.Kategori.ToList();
return View(kat);
}
public ActionResult TumMakalelerGetir()
{
var makaleler = context.Makale.ToList();
return View("MakaleListele", makaleler);//makalelistele bi partial view
}
}
}
this is my model:
namespace mvcblogdeneme.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Makale")]
public partial class Makale
{
public int Id { get; set; }
[Required]
[StringLength(150)]
public string Baslik { get; set; }
[Required]
public string Icerik { get; set; }
public DateTime YayimTarihi { get; set; }
public int KategoriID { get; set; }
public virtual Kategori Kategori { get; set; }
}
}
If the exception message shows like this and DbContext is being used:
EntityType '[[table name]]' has no key defined. Define the key for
this EntityType.
EntityType: EntitySet '[[entity name]]' is based on type '[[table name]]'
that has no keys defined.
Then definitely you need to use KeyAttribute on Id property to mark it as primary key field inside table model class and problem will solved:
[Table("Makale")]
public partial class Makale
{
// if the ID also set as auto-increment, uncomment DatabaseGenerated attribute given below
// [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Id { get; set; }
[Required]
[StringLength(150)]
public string Baslik { get; set; }
[Required]
public string Icerik { get; set; }
public DateTime YayimTarihi { get; set; }
public int KategoriID { get; set; }
public virtual Kategori Kategori { get; set; }
}
However, if the cause is found out coming from IdentityDbContext and EF Code First being used, you need to do these steps (credits to DotNetHaggis):
Create configuration class for IdentityUserLogin & IdentityUserRole:
// taken from /a/20912641
public class IdentityUserLoginConfiguration : EntityTypeConfiguration<IdentityUserLogin>
{
public IdentityUserLoginConfiguration()
{
HasKey(iul => iul.UserId);
}
}
public class IdentityUserRoleConfiguration : EntityTypeConfiguration<IdentityUserRole>
{
public IdentityUserRoleConfiguration()
{
HasKey(iur => iur.RoleId);
}
}
Add those two configurations above inside OnModelCreating method:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new IdentityUserLoginConfiguration());
modelBuilder.Configurations.Add(new IdentityUserRoleConfiguration());
}
At this point, the error should get resolved due to primary key for every identity tables has been set.
Similar issues:
An exception of type 'System.Data.Entity.ModelConfiguration.ModelValidationException' occurred in EntityFramework.dll
Merge MyDbContext with IdentityDbContext

create new controller - error running selected code generator

I am using Visual Studio Express 2013 for Web (specifically version 12.0.21005.1 REL). This is my first project using VS2013, I've been using VS2012 up until this point.
I am attempting to create a new controller in my asp.net MVC application. I am using Entity Framework 5 with code first (.NET 4.5). I want Visual Studio to create the template for me (you know, a controller with views to read/write/delete etc, rather than write the code myself from scratch).
However, every time I try to create the controller I get the following error message:
Is there some sort of bug in VS 2013? I can't figure out what this means, and restarting VS2013 does not help.
Here are the gory details.... actually it is all very simple since this is a new project with very little code written so far.
My model:
namespace ProfessionalSite.Models
{
public class EntityModels
{
public class Student
{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
public class Enrollment
{
public int ID { get; set; }
public string EnrollmentName { get; set; }
public string Credits { get; set; }
}
// Create the class that inherits from DbContext
// The name of this class is also used as the connection string in web.config
public class EFDbContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
}
}
}
And in my web.config file I have the following
<add name="EFDbContext"
connectionString="Data Source=JONSNA\SQLEXP2012WT;Initial Catalog=ProfessionalSiteDb; Integrated Security=True; MultipleActiveResultSets=True"
providerName="System.Data.SqlClient"/>
within the tags.
Now time to create a controller. I right click on Controllers in the Solution Explorer, and choose to Add a new Controller.
And then
And when I click Add I get
I cant figure out how to get rid of this error. I guess as a workaround I can just type the code myself, but I'd like to know if this is a bug or something I have done wrong. In VS2012 this just worked...
I'd appreciate any help or pointers. Thanks.
You don't need the EntityModels class, See below:
namespace ProfessionalSite.Models
{
public class Student
{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
public class Enrollment
{
public int ID { get; set; }
public string EnrollmentName { get; set; }
public string Credits { get; set; }
}
// Create the class that inherits from DbContext
// The name of this class is also used as the connection string in web.config
public class EFDbContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
}
}
Then when you create a controller, just select the Student or Enrollment for the Model class.

Entity Model, grouping models in one model file

I have the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MyTestWebsite.Models
{
public class Page
{
public int Id { get; set; }
public int AuthorUserId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Content { get; set; }
public bool Hidden { get; set; }
}
public class PageState
{
public int Id { get; set; }
public string Type { get; set; }
}
public class MyTestWebsiteDBContext : DbContext
{
public DbSet<Page> Pages { get; set; }
public DbSet<PageState> PageStates { get; set; }
}
}
I went to create a controller for Page and I found the model structure.. no problems.
This is, I need another model called PageState and my model list does not show this second model.
Is it usual to have a heck load of models.... regardless of them being linked in some way?
Do I just add a model on its own called PageState?
Is it usual to have a heck load of models
Yes, they are called view models. Each view should have a specific view model. It's perfectly normal to have many view models if you have many views. A view model could aggregate one or more of your EF domain models.

Resources